lib3to2 / lib3to2 / fixes /

Fixer for:
str -> unicode
chr -> unichr
"spam" -> u"spam"

import re
from lib2to3.pgen2 import token
from lib2to3 import fixer_base
from lib2to3.fixer_util import Name

_mapping = {"chr": "unichr", "str": "unicode"}
_literal_re = re.compile(r"[rR]?[\'\"]")

class FixStr(fixer_base.BaseFix):

    order = "pre"
    run_order = 4 # Run this before bytes objects are converted to str objects

    PATTERN = "STRING | 'str' | 'chr'"

    def transform(self, node, results):
        new = node.clone()
        if node.type == token.STRING:
            # Simply add u to the beginning of the literal.
            if _literal_re.match(new.value):
                new.value = "u" + new.value
                return new
        elif node.type == token.NAME:
            assert new.value in _mapping
            new.value = _mapping[new.value]
            return new
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.