fix_oldstr_wrap.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. """
  2. For the ``future`` package.
  3. Adds this import line:
  4. from past.builtins import str as oldstr
  5. at the top and wraps any unadorned string literals 'abc' or explicit byte-string
  6. literals b'abc' in oldstr() calls so the code has the same behaviour on Py3 as
  7. on Py2.6/2.7.
  8. """
  9. from __future__ import unicode_literals
  10. import re
  11. from lib2to3 import fixer_base
  12. from lib2to3.pgen2 import token
  13. from lib2to3.fixer_util import syms
  14. from libfuturize.fixer_util import (future_import, touch_import_top,
  15. wrap_in_fn_call)
  16. _literal_re = re.compile(r"[^uUrR]?[\'\"]")
  17. class FixOldstrWrap(fixer_base.BaseFix):
  18. BM_compatible = True
  19. PATTERN = "STRING"
  20. def transform(self, node, results):
  21. if node.type == token.STRING:
  22. touch_import_top(u'past.types', u'oldstr', node)
  23. if _literal_re.match(node.value):
  24. new = node.clone()
  25. # Strip any leading space or comments:
  26. # TODO: check: do we really want to do this?
  27. new.prefix = u''
  28. new.value = u'b' + new.value
  29. wrapped = wrap_in_fn_call("oldstr", [new], prefix=node.prefix)
  30. return wrapped