micropython

tests/visitor_getattr.py

442:13aae946513b
2011-07-05 Paul Boddie Introduced Instance() in place of None as a result and for the value of the active expression where no definitive object can be deduced. Made all Instance values compare equal to each other in order to avoid duplication in sets. Improved Constant comparisons. Fixed assignment counting where many values are provided in a single assignment. Added inspection support for conditional expressions (since they are used in the standard library).
     1 #!/usr/bin/env python     2      3 class Branch:     4     def __init__(self, nodes):     5         self.nodes = nodes     6      7 class Leaf:     8     def __init__(self, value):     9         self.value = value    10     11 class Visitor:    12     def visit(self, node):    13         method = getattr(self, node.__class__.__name__)    14         return method(node)    15     16     # Visitor-specific functionality.    17     # Note that getattr does not support "visit" + __class__.__name__.    18     19     def Branch(self, node):    20         sum = 0    21         for node in node.nodes:    22             sum += self.visit(node)    23         return sum    24     25     def Leaf(self, node):    26         return node.value    27     28 tree = \    29     Branch((    30         Branch((    31             Leaf(10),    32             Leaf(5)    33             )),    34         Leaf(2)    35         ))    36     37 visitor = Visitor()    38 result_17 = visitor.visit(tree)    39     40 # vim: tabstop=4 expandtab shiftwidth=4