File: fix_unicode.py

package info (click to toggle)
python-django 1.7.7-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 44,872 kB
  • sloc: python: 170,757; xml: 713; makefile: 199; sh: 170; sql: 11
file content (36 lines) | stat: -rw-r--r-- 1,181 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""Fixer for __unicode__ methods.

Uses the django.utils.encoding.python_2_unicode_compatible decorator.
"""

from __future__ import unicode_literals

from lib2to3 import fixer_base
from lib2to3.fixer_util import find_indentation, Name, syms, touch_import
from lib2to3.pgen2 import token
from lib2to3.pytree import Leaf, Node


class FixUnicode(fixer_base.BaseFix):

    BM_compatible = True
    PATTERN = """
    classdef< 'class' any+ ':'
              suite< any*
                     funcdef< 'def' unifunc='__unicode__'
                              parameters< '(' NAME ')' > any+ >
                     any* > >
    """

    def transform(self, node, results):
        unifunc = results["unifunc"]
        strfunc = Name("__str__", prefix=unifunc.prefix)
        unifunc.replace(strfunc)

        klass = node.clone()
        klass.prefix = '\n' + find_indentation(node)
        decorator = Node(syms.decorator, [Leaf(token.AT, "@"), Name('python_2_unicode_compatible')])
        decorated = Node(syms.decorated, [decorator, klass], prefix=node.prefix)
        node.replace(decorated)

        touch_import('django.utils.encoding', 'python_2_unicode_compatible', decorated)