Decorator Syntax For Recursive Properties

Jeffrey Froman jeffrey at fro.man
Sun Apr 17 02:28:13 EDT 2005


Consider the following class:

class Node(object):
    def __init__(self, name, parent=None):
        self.name = name
        self.parent = parent

    def _ancestors(self, ants=None):
        if ants is None:
            ants = []
        else:
            ants.insert(0, self.name)
        if self.parent is None:
            return ants
        return self.parent._ancestors(ants)
    ancestors = property(_ancestors)

The ancestor property generates a list ancestor nodes by having each parent
examine its own name recursively. The recursion is managed by calling the
method underlying the parent property, rather than calling the property
directly.

Is it possible to rewrite this property using decorator syntax? Does the
@property decorator create some underlying method that I can call directly?

Alternately, perhaps there is a way to rewrite the recursion so that such a
call is unnecessary? Note that the property should not add its own name if
it is the originating node (the node trying to find _its_ ancestors). So
something like this didn't work for me:

    @property
    def ancestors(self):
        if self.parent is None:
            return [self.name]
        return [self.name] + self.parent.ancestors

In other words, since there is no longer a list passing from child to parent
during the recursion, is there a graceful way to examine the state of the
ancestor list so far?


Thanks,
Jeffrey



More information about the Python-list mailing list