fix_paren.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """Fixer that adds parentheses where they are required
  2. This converts ``[x for x in 1, 2]`` to ``[x for x in (1, 2)]``."""
  3. # By Taek Joo Kim and Benjamin Peterson
  4. # Local imports
  5. from .. import fixer_base
  6. from ..fixer_util import LParen, RParen
  7. # XXX This doesn't support nested for loops like [x for x in 1, 2 for x in 1, 2]
  8. class FixParen(fixer_base.BaseFix):
  9. BM_compatible = True
  10. PATTERN = """
  11. atom< ('[' | '(')
  12. (listmaker< any
  13. comp_for<
  14. 'for' NAME 'in'
  15. target=testlist_safe< any (',' any)+ [',']
  16. >
  17. [any]
  18. >
  19. >
  20. |
  21. testlist_gexp< any
  22. comp_for<
  23. 'for' NAME 'in'
  24. target=testlist_safe< any (',' any)+ [',']
  25. >
  26. [any]
  27. >
  28. >)
  29. (']' | ')') >
  30. """
  31. def transform(self, node, results):
  32. target = results["target"]
  33. lparen = LParen()
  34. lparen.prefix = target.prefix
  35. target.prefix = "" # Make it hug the parentheses
  36. target.insert_child(0, lparen)
  37. target.append_child(RParen())