Python lib2to3.fixer_util.Name() Examples

The following are 30 code examples of lib2to3.fixer_util.Name(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module lib2to3.fixer_util , or try the search function .
Example #1
Source File: fix_UserDict.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def transform(self, node, results):
        import_mod = results.get("module_name")
        if import_mod:
            mod_name = import_mod.value
            new_name = unicode(self.mapping[mod_name])
            import_mod.replace(Name(new_name, prefix=import_mod.prefix))
            if "name_import" in results:
                # If it's not a "from x import x, y" or "import x as y" import,
                # marked its usage to be replaced.
                self.replace[mod_name] = new_name
            if "multiple_imports" in results:
                # This is a nasty hack to fix multiple imports on a line (e.g.,
                # "import StringIO, urlparse"). The problem is that I can't
                # figure out an easy way to make a pattern recognize the keys of
                # MAPPING randomly sprinkled in an import statement.
                results = self.match(node)
                if results:
                    self.transform(node, results)
        else:
            # Replace usage of the module.
            bare_name = results["bare_with_attr"][0]
            new_name = self.replace.get(bare_name.value)
            if new_name:
                bare_name.replace(Name(new_name, prefix=bare_name.prefix)) 
Example #2
Source File: fix_callable.py    From Computable with MIT License 5 votes vote down vote up
def transform(self, node, results):
        func = results['func']

        touch_import(None, u'collections', node=node)

        args = [func.clone(), String(u', ')]
        args.extend(Attr(Name(u'collections'), Name(u'Callable')))
        return Call(Name(u'isinstance'), args, prefix=node.prefix) 
Example #3
Source File: fix_memoryview.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def transform(self, node, results):
        name = results[u"name"]
        name.replace(Name(u"buffer", prefix=name.prefix)) 
Example #4
Source File: fix_operator.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def _handle_type2abc(self, node, results, module, abc):
        touch_import(None, module, node)
        obj = results["obj"]
        args = [obj.clone(), String(u", " + u".".join([module, abc]))]
        return Call(Name(u"isinstance"), args, prefix=node.prefix) 
Example #5
Source File: fix_next_call.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def transform(self, node, results):
        assert results

        base = results.get("base")
        attr = results.get("attr")
        name = results.get("name")

        if base:
            if self.shadowed_next:
                # Omit this:
                # attr.replace(Name("__next__", prefix=attr.prefix))
                pass
            else:
                base = [n.clone() for n in base]
                base[0].prefix = ""
                node.replace(Call(Name("next", prefix=node.prefix), base))
        elif name:
            # Omit this:
            # n = Name("__next__", prefix=name.prefix)
            # name.replace(n)
            pass
        elif attr:
            # We don't do this transformation if we're assigning to "x.next".
            # Unfortunately, it doesn't seem possible to do this in PATTERN,
            #  so it's being done here.
            if is_assign_target(node):
                head = results["head"]
                if "".join([str(n) for n in head]).strip() == '__builtin__':
                    self.warning(node, bind_warning)
                return
            # Omit this:
            # attr.replace(Name("__next__"))
        elif "global" in results:
            self.warning(node, bind_warning)
            self.shadowed_next = True


### The following functions help test if node is part of an assignment
###  target. 
Example #6
Source File: fix_raise.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def transform(self, node, results):
        syms = self.syms

        exc = results["exc"].clone()
        if exc.type == token.STRING:
            msg = "Python 3 does not support string exceptions"
            self.cannot_convert(node, msg)
            return

        # Python 2 supports
        #  raise ((((E1, E2), E3), E4), E5), V
        # as a synonym for
        #  raise E1, V
        # Since Python 3 will not support this, we recurse down any tuple
        # literals, always taking the first element.
        if is_tuple(exc):
            while is_tuple(exc):
                # exc.children[1:-1] is the unparenthesized tuple
                # exc.children[1].children[0] is the first element of the tuple
                exc = exc.children[1].children[0].clone()
            exc.prefix = u" "

        if "val" not in results:
            # One-argument raise
            new = pytree.Node(syms.raise_stmt, [Name(u"raise"), exc])
            new.prefix = node.prefix
            return new

        val = results["val"].clone()
        if is_tuple(val):
            args = [c.clone() for c in val.children[1:-1]]
        else:
            val.prefix = u""
            args = [val]

        return pytree.Node(syms.raise_stmt,
                           [Name(u"raise"), Call(exc, args)],
                           prefix=node.prefix) 
Example #7
Source File: fix_getcwd.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def transform(self, node, results):
        if u"name" in results:
            name = results[u"name"]
            name.replace(Name(u"getcwdu", prefix=name.prefix))
        elif u"bad" in results:
            # Can't convert to getcwdu and then expect to catch every use.
            self.cannot_convert(node, u"import os, use os.getcwd() instead.")
            return
        else:
            raise ValueError(u"For some reason, the pattern matcher failed.") 
Example #8
Source File: fix_newstyle.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def insert_object(node, idx):
    node.insert_child(idx, RParen())
    node.insert_child(idx, Name(u"object"))
    node.insert_child(idx, LParen()) 
Example #9
Source File: fix_fullargspec.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def transform(self, node, results):
        self.warning(node, warn_msg)
        return Name(u"getargspec", prefix=node.prefix) 
Example #10
Source File: fix_exitfunc.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def transform(self, node, results):
        # First, find a the sys import. We'll just hope it's global scope.
        if "sys_import" in results:
            if self.sys_import is None:
                self.sys_import = results["sys_import"]
            return

        func = results["func"].clone()
        func.prefix = u""
        register = pytree.Node(syms.power,
                               Attr(Name(u"atexit"), Name(u"register"))
                               )
        call = Call(register, [func], node.prefix)
        node.replace(call)

        if self.sys_import is None:
            # That's interesting.
            self.warning(node, "Can't find sys import; Please add an atexit "
                             "import at the top of your file.")
            return

        # Now add an atexit import after the sys import.
        names = self.sys_import.children[1]
        if names.type == syms.dotted_as_names:
            names.append_child(Comma())
            names.append_child(Name(u"atexit", u" "))
        else:
            containing_stmt = self.sys_import.parent
            position = containing_stmt.children.index(self.sys_import)
            stmt_container = containing_stmt.parent
            new_import = pytree.Node(syms.import_name,
                              [Name(u"import"), Name(u"atexit", u" ")]
                              )
            new = pytree.Node(syms.simple_stmt, [new_import])
            containing_stmt.insert_child(position + 1, Newline())
            containing_stmt.insert_child(position + 2, new) 
Example #11
Source File: fix_callable.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def transform(self, node, results):
        func = results['func']

        touch_import(None, u'collections', node=node)

        args = [func.clone(), String(u', ')]
        args.extend(Attr(Name(u'collections'), Name(u'Callable')))
        return Call(Name(u'isinstance'), args, prefix=node.prefix) 
Example #12
Source File: fix_next.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def transform(self, node, results):
        assert results

        base = results.get(u"base")
        attr = results.get(u"attr")
        head = results.get(u"head")
        arg_ = results.get(u"arg")
        if arg_:
            arg = arg_.clone()
            head.replace(Attr(Name(unicode(arg),prefix=head.prefix),
                              Name(u"next")))
            arg_.remove()
        elif base:
            attr.replace(Name(u"next", prefix=attr.prefix)) 
Example #13
Source File: test_util.py    From Computable with MIT License 5 votes vote down vote up
def _Call(self, name, args=None, prefix=None):
        """Help the next test"""
        children = []
        if isinstance(args, list):
            for arg in args:
                children.append(arg)
                children.append(Comma())
            children.pop()
        return Call(Name(name), children, prefix) 
Example #14
Source File: test_util.py    From Computable with MIT License 5 votes vote down vote up
def test(self):
        self.assertStr(Name("a"), "a")
        self.assertStr(Name("foo.foo().bar"), "foo.foo().bar")
        self.assertStr(Name("a", prefix="b"), "ba") 
Example #15
Source File: test_util.py    From Computable with MIT License 5 votes vote down vote up
def test(self):
        call = parse("foo()", strip_levels=2)

        self.assertStr(Attr(Name("a"), Name("b")), "a.b")
        self.assertStr(Attr(call, Name("b")), "foo().b") 
Example #16
Source File: fix_exitfunc.py    From Computable with MIT License 5 votes vote down vote up
def transform(self, node, results):
        # First, find a the sys import. We'll just hope it's global scope.
        if "sys_import" in results:
            if self.sys_import is None:
                self.sys_import = results["sys_import"]
            return

        func = results["func"].clone()
        func.prefix = u""
        register = pytree.Node(syms.power,
                               Attr(Name(u"atexit"), Name(u"register"))
                               )
        call = Call(register, [func], node.prefix)
        node.replace(call)

        if self.sys_import is None:
            # That's interesting.
            self.warning(node, "Can't find sys import; Please add an atexit "
                             "import at the top of your file.")
            return

        # Now add an atexit import after the sys import.
        names = self.sys_import.children[1]
        if names.type == syms.dotted_as_names:
            names.append_child(Comma())
            names.append_child(Name(u"atexit", u" "))
        else:
            containing_stmt = self.sys_import.parent
            position = containing_stmt.children.index(self.sys_import)
            stmt_container = containing_stmt.parent
            new_import = pytree.Node(syms.import_name,
                              [Name(u"import"), Name(u"atexit", u" ")]
                              )
            new = pytree.Node(syms.simple_stmt, [new_import])
            containing_stmt.insert_child(position + 1, Newline())
            containing_stmt.insert_child(position + 2, new) 
Example #17
Source File: fix_parrot.py    From Computable with MIT License 5 votes vote down vote up
def transform(self, node, results):
        name = results["name"]
        name.replace(Name("cheese", name.prefix)) 
Example #18
Source File: fix_operator.py    From Computable with MIT License 5 votes vote down vote up
def _handle_type2abc(self, node, results, module, abc):
        touch_import(None, module, node)
        obj = results["obj"]
        args = [obj.clone(), String(u", " + u".".join([module, abc]))]
        return Call(Name(u"isinstance"), args, prefix=node.prefix) 
Example #19
Source File: fix_operator.py    From Computable with MIT License 5 votes vote down vote up
def _isCallable(self, node, results):
        obj = results["obj"]
        args = [obj.clone(), String(u", "), String(u"'__call__'")]
        return Call(Name(u"hasattr"), args, prefix=node.prefix) 
Example #20
Source File: fix_exitfunc.py    From BinderFilter with MIT License 5 votes vote down vote up
def transform(self, node, results):
        # First, find a the sys import. We'll just hope it's global scope.
        if "sys_import" in results:
            if self.sys_import is None:
                self.sys_import = results["sys_import"]
            return

        func = results["func"].clone()
        func.prefix = u""
        register = pytree.Node(syms.power,
                               Attr(Name(u"atexit"), Name(u"register"))
                               )
        call = Call(register, [func], node.prefix)
        node.replace(call)

        if self.sys_import is None:
            # That's interesting.
            self.warning(node, "Can't find sys import; Please add an atexit "
                             "import at the top of your file.")
            return

        # Now add an atexit import after the sys import.
        names = self.sys_import.children[1]
        if names.type == syms.dotted_as_names:
            names.append_child(Comma())
            names.append_child(Name(u"atexit", u" "))
        else:
            containing_stmt = self.sys_import.parent
            position = containing_stmt.children.index(self.sys_import)
            stmt_container = containing_stmt.parent
            new_import = pytree.Node(syms.import_name,
                              [Name(u"import"), Name(u"atexit", u" ")]
                              )
            new = pytree.Node(syms.simple_stmt, [new_import])
            containing_stmt.insert_child(position + 1, Newline())
            containing_stmt.insert_child(position + 2, new) 
Example #21
Source File: fix_callable.py    From BinderFilter with MIT License 5 votes vote down vote up
def transform(self, node, results):
        func = results['func']

        touch_import(None, u'collections', node=node)

        args = [func.clone(), String(u', ')]
        args.extend(Attr(Name(u'collections'), Name(u'Callable')))
        return Call(Name(u'isinstance'), args, prefix=node.prefix) 
Example #22
Source File: fix_operator.py    From BinderFilter with MIT License 5 votes vote down vote up
def _handle_type2abc(self, node, results, module, abc):
        touch_import(None, module, node)
        obj = results["obj"]
        args = [obj.clone(), String(u", " + u".".join([module, abc]))]
        return Call(Name(u"isinstance"), args, prefix=node.prefix) 
Example #23
Source File: fix_operator.py    From BinderFilter with MIT License 5 votes vote down vote up
def _isCallable(self, node, results):
        obj = results["obj"]
        args = [obj.clone(), String(u", "), String(u"'__call__'")]
        return Call(Name(u"hasattr"), args, prefix=node.prefix) 
Example #24
Source File: fix_parrot.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def transform(self, node, results):
        name = results["name"]
        name.replace(Name("cheese", name.prefix)) 
Example #25
Source File: test_util.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _Call(self, name, args=None, prefix=None):
        """Help the next test"""
        children = []
        if isinstance(args, list):
            for arg in args:
                children.append(arg)
                children.append(Comma())
            children.pop()
        return Call(Name(name), children, prefix) 
Example #26
Source File: test_util.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_returns(self):
        attr = Attr(Name("a"), Name("b"))
        self.assertEqual(type(attr), list) 
Example #27
Source File: test_util.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test(self):
        call = parse("foo()", strip_levels=2)

        self.assertStr(Attr(Name("a"), Name("b")), "a.b")
        self.assertStr(Attr(call, Name("b")), "foo().b") 
Example #28
Source File: fix_exitfunc.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def transform(self, node, results):
        # First, find the sys import. We'll just hope it's global scope.
        if "sys_import" in results:
            if self.sys_import is None:
                self.sys_import = results["sys_import"]
            return

        func = results["func"].clone()
        func.prefix = u""
        register = pytree.Node(syms.power,
                               Attr(Name(u"atexit"), Name(u"register"))
                               )
        call = Call(register, [func], node.prefix)
        node.replace(call)

        if self.sys_import is None:
            # That's interesting.
            self.warning(node, "Can't find sys import; Please add an atexit "
                             "import at the top of your file.")
            return

        # Now add an atexit import after the sys import.
        names = self.sys_import.children[1]
        if names.type == syms.dotted_as_names:
            names.append_child(Comma())
            names.append_child(Name(u"atexit", u" "))
        else:
            containing_stmt = self.sys_import.parent
            position = containing_stmt.children.index(self.sys_import)
            stmt_container = containing_stmt.parent
            new_import = pytree.Node(syms.import_name,
                              [Name(u"import"), Name(u"atexit", u" ")]
                              )
            new = pytree.Node(syms.simple_stmt, [new_import])
            containing_stmt.insert_child(position + 1, Newline())
            containing_stmt.insert_child(position + 2, new) 
Example #29
Source File: fix_operator.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _handle_type2abc(self, node, results, module, abc):
        touch_import(None, module, node)
        obj = results["obj"]
        args = [obj.clone(), String(u", " + u".".join([module, abc]))]
        return Call(Name(u"isinstance"), args, prefix=node.prefix) 
Example #30
Source File: fix_operator.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _isCallable(self, node, results):
        obj = results["obj"]
        args = [obj.clone(), String(u", "), String(u"'__call__'")]
        return Call(Name(u"hasattr"), args, prefix=node.prefix)