fix_unicode.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. """Fixer for __unicode__ methods.
  2. Uses the django.utils.encoding.python_2_unicode_compatible decorator.
  3. """
  4. from __future__ import unicode_literals
  5. from lib2to3 import fixer_base
  6. from lib2to3.fixer_util import find_indentation, Name, syms, touch_import
  7. from lib2to3.pgen2 import token
  8. from lib2to3.pytree import Leaf, Node
  9. class FixUnicode(fixer_base.BaseFix):
  10. BM_compatible = True
  11. PATTERN = """
  12. classdef< 'class' any+ ':'
  13. suite< any*
  14. funcdef< 'def' unifunc='__unicode__'
  15. parameters< '(' NAME ')' > any+ >
  16. any* > >
  17. """
  18. def transform(self, node, results):
  19. unifunc = results["unifunc"]
  20. strfunc = Name("__str__", prefix=unifunc.prefix)
  21. unifunc.replace(strfunc)
  22. klass = node.clone()
  23. klass.prefix = '\n' + find_indentation(node)
  24. decorator = Node(syms.decorator, [Leaf(token.AT, "@"), Name('python_2_unicode_compatible')])
  25. decorated = Node(syms.decorated, [decorator, klass], prefix=node.prefix)
  26. node.replace(decorated)
  27. touch_import('django.utils.encoding', 'python_2_unicode_compatible', decorated)