fix_annotations.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. u"""
  2. Fixer to remove function annotations
  3. """
  4. from lib2to3 import fixer_base
  5. from lib2to3.pgen2 import token
  6. from lib2to3.fixer_util import syms
  7. warning_text = u"Removing function annotations completely."
  8. def param_without_annotations(node):
  9. return node.children[0]
  10. class FixAnnotations(fixer_base.BaseFix):
  11. warned = False
  12. def warn_once(self, node, reason):
  13. if not self.warned:
  14. self.warned = True
  15. self.warning(node, reason=reason)
  16. PATTERN = u"""
  17. funcdef< 'def' any parameters< '(' [params=any] ')' > ['->' ret=any] ':' any* >
  18. """
  19. def transform(self, node, results):
  20. u"""
  21. This just strips annotations from the funcdef completely.
  22. """
  23. params = results.get(u"params")
  24. ret = results.get(u"ret")
  25. if ret is not None:
  26. assert ret.prev_sibling.type == token.RARROW, u"Invalid return annotation"
  27. self.warn_once(node, reason=warning_text)
  28. ret.prev_sibling.remove()
  29. ret.remove()
  30. if params is None: return
  31. if params.type == syms.typedargslist:
  32. # more than one param in a typedargslist
  33. for param in params.children:
  34. if param.type == syms.tname:
  35. self.warn_once(node, reason=warning_text)
  36. param.replace(param_without_annotations(param))
  37. elif params.type == syms.tname:
  38. # one param
  39. self.warn_once(node, reason=warning_text)
  40. params.replace(param_without_annotations(params))