How to use the astor.TreeWalk function in astor

To help you get started, we’ve selected a few astor examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github berkerpeksag / astor / tests / test_misc.py View on Github external
def test_auto_generated_attributes(self):
        # See #136 for more details.
        treewalk = astor.TreeWalk()
        self.assertIsInstance(treewalk.__dict__, dict)
        # Check that the inital state of the instance is empty.
        self.assertEqual(treewalk.__dict__['nodestack'], [])
        self.assertEqual(treewalk.__dict__['pre_handlers'], {})
        self.assertEqual(treewalk.__dict__['post_handlers'], {})
github berkerpeksag / astor / tests / test_transform.py View on Github external
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import astor

def TestMe(x, y, width=10, foo=None):
    from foo.bar.baz.murgatroyd import sally as bob

    a.b = c.d + x.y.z.a.b
    m.n = q = (w.w, x.x.y.y) = f(x.x.y.z)

func_ast = astor.codetoast(TestMe)
print(astor.dump(func_ast))
print(astor.to_source(func_ast))

class ConsolidateAttributes(astor.TreeWalk):
    def post_Attribute(self):
        node = self.cur_node
        value = node.value
        value.id += '.' + node.attr
        self.replace(value)

ConsolidateAttributes(func_ast)

class FindNames(astor.TreeWalk):
    def init_Assign(self):
        self.assignments = []
        self.current_assign = None
    def pre_Assign(self):
        self.current_assign = [], []
    def post_Assign(self):
        self.assignments.append(self.current_assign)
github berkerpeksag / astor / tests / test_transform.py View on Github external
m.n = q = (w.w, x.x.y.y) = f(x.x.y.z)

func_ast = astor.codetoast(TestMe)
print(astor.dump(func_ast))
print(astor.to_source(func_ast))

class ConsolidateAttributes(astor.TreeWalk):
    def post_Attribute(self):
        node = self.cur_node
        value = node.value
        value.id += '.' + node.attr
        self.replace(value)

ConsolidateAttributes(func_ast)

class FindNames(astor.TreeWalk):
    def init_Assign(self):
        self.assignments = []
        self.current_assign = None
    def pre_Assign(self):
        self.current_assign = [], []
    def post_Assign(self):
        self.assignments.append(self.current_assign)
        self.current_assign = None

    def pre_targets_name(self):
        self.in_targets = True
    def post_targets_name(self):
        self.in_targets = False
    def post_Name(self):
        if self.current_assign:
            self.current_assign[self.in_targets].append(self.cur_node.id)