Changing self: if self is a tree how to set to a different self

Terry Reedy tjreedy at udel.edu
Thu Jul 10 14:29:32 EDT 2008



Bart Kastermans wrote:
> I am playing with some trees.  In one of the procedures I wrote
> for this I am trying to change self to a different tree.  A tree
> here has four members (val/type/left/right).  I found that self = SS
> does not work; I have to write self.val = SS.val and the same for
> the other members (as shown below).  Is there a better way to do this?
> 
> In the below self is part of a parse tree, F is the parse tree of a
> function f with argument x.  If a node in the parse tree is labelled
> f, we should replace it by the parse tree for the function f, F, with
> the remainder of the tree substituted for the input variable for the
> function f, here x.
> 
>     def elimF (self):
>         if self.val == "f":
>             SS = F.copy ()
>             SS.subst ('x', self.left)
>             self.val = SS.val        # from here: set self to be SS
>             self.type = SS.type
>             self.left = SS.left
>             self.right = SS.right    # completed: set self to be SS

If you examine nodes from their parent, I believe you can do the 
substitution in one step. Something like:

for slot,child in ( ('left',self.left), ('right',self.right) ):
   if child is not None:
     if child.val == 'f':
       setattr(self, slot, F.copy().subst('x', child.left))
     child.elimF

where .subst returns the modified tree.

> 
>         if self.left != None:        # iterate onward, inf recursion if f
>                                      # appears.  Would need a check in
>                                      # real version
>             self.left.elimF ()
>         if self.right != None:
>             self.right.elimF ()

Terry Jan Reedy




More information about the Python-list mailing list