Recursive class | can you modify self directly?

Ian Kelly ian.g.kelly at gmail.com
Wed Jul 10 19:39:04 EDT 2013


On Wed, Jul 10, 2013 at 4:50 PM, Russel Walker <russ.pobox at gmail.com> wrote:
>     def append(self, x):
>         if len(self) < 3:
>             list.append(self, x)
>         else:
>             oldself = LRExpression(*self)
>             self.__init__(oldself)
>             self.append(x)

It's probably not wise to be re-calling __init__ after the class has
been initialized, although it seems to work.  I would instead use
slice assignment to replace the list contents:

    self[:] = [oldself]

That said, the problem with inheriting from list is that it allows
your class to be used in a lot of ways lists can be used that are
probably not appropriate.  For example, continuing on from your test
function:

>>> len(a)
3

Why 3?  Because that's the length of the list.  But the caller would
probably expect the length to have something to do with the size of
the expression, not the list.

>>> '*' in a   # Is the '*' operator used in a?
True
>>> '+' in a   # What about the '+' operator?
False

Again, this happens because the "in" operator is only looking at the
list itself, not at sublists.  But an expression container would
probably be expected to return True for both of those.  These cases
can of course be easily overridden in the subclass, but what about
something harder, like slicing?  How should that be expected to work
with an LRExpression?

This isn't to say that you shouldn't necessarily use a list if it
helps you implement the behavior you want, but having the LRExpression
*be* a list is probably wrong.


Finally, based on what you're doing here, I think you would be better
off using something like the OOP Builder pattern.  There will be two
distinct classes: the "LRExpression" class that composes a tree
structure, and an "ExpressionBuilder" class that does the work of
actual assembly.  It could look something like this:

class LRExpression(object):
    def __init__(self, expr, op, value):
        self.expr = expr
        self.op = op
        self.value = value
    def __str__(self):
        return '(%s %s %s)' % (self.expr, self.op, self.value)
    def evaluate(self):
        # Subject to the usual warning that eval() should
        # never be used with untrusted input
        return eval(str(self))

class ExpressionBuilder(object):
    def __init__(self):
        self.parts = []
    def append(self, part):
        self.parts.append(part)
    def build(self):
        expr = self.parts[0]
        for i in xrange(1, len(self.parts), 2):
            op, value = self.parts[i:i+2]
            expr = LRExpression(expr, op, value)
        return expr

def test():
    a = ExpressionBuilder()
    a.append(1)
    a.append('+')
    a.append(2)
    a.append('*')
    a.append(3)
    expr = a.build()
    print expr
    print expr.evaluate()

>>> test()
((1 + 2) * 3)
9



More information about the Python-list mailing list