fix_future_builtins.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """
  2. For the ``future`` package.
  3. Adds this import line::
  4. from builtins import XYZ
  5. for each of the functions XYZ that is used in the module.
  6. Adds these imports after any other imports (in an initial block of them).
  7. """
  8. from __future__ import unicode_literals
  9. from lib2to3 import fixer_base
  10. from lib2to3.pygram import python_symbols as syms
  11. from lib2to3.fixer_util import Name, Call, in_special_context
  12. from libfuturize.fixer_util import touch_import_top
  13. # All builtins are:
  14. # from future.builtins.iterators import (filter, map, zip)
  15. # from future.builtins.misc import (ascii, chr, hex, input, isinstance, oct, open, round, super)
  16. # from future.types import (bytes, dict, int, range, str)
  17. # We don't need isinstance any more.
  18. replaced_builtin_fns = '''filter map zip
  19. ascii chr hex input next oct
  20. bytes range str raw_input'''.split()
  21. # This includes raw_input as a workaround for the
  22. # lib2to3 fixer for raw_input on Py3 (only), allowing
  23. # the correct import to be included. (Py3 seems to run
  24. # the fixers the wrong way around, perhaps ignoring the
  25. # run_order class attribute below ...)
  26. expression = '|'.join(["name='{0}'".format(name) for name in replaced_builtin_fns])
  27. class FixFutureBuiltins(fixer_base.BaseFix):
  28. BM_compatible = True
  29. run_order = 7
  30. # Currently we only match uses as a function. This doesn't match e.g.:
  31. # if isinstance(s, str):
  32. # ...
  33. PATTERN = """
  34. power<
  35. ({0}) trailer< '(' [arglist=any] ')' >
  36. rest=any* >
  37. |
  38. power<
  39. 'map' trailer< '(' [arglist=any] ')' >
  40. >
  41. """.format(expression)
  42. def transform(self, node, results):
  43. name = results["name"]
  44. touch_import_top(u'builtins', name.value, node)
  45. # name.replace(Name(u"input", prefix=name.prefix))