Decorator Syntax For Recursive Properties

Peter Otten __peter__ at web.de
Sun Apr 17 15:56:02 EDT 2005


Jeffrey Froman wrote:

> 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

But this will, I suppose:

@property
def ancestors(self):
    if self.parent:
        return self.parent.ancestors + [self.parent]
    return []
 
A non-recursive variant:

@property
def ancestors(self):
    result = []
    node = self.parent
    while node:
        result.append(node)
        node = node.parent
    result.reverse()
    return result

Peter




More information about the Python-list mailing list