473,796 Members | 2,501 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Decorator Syntax For Recursive Properties

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._an cestors(ants)
ancestors = property(_ances tors)

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.anc estors

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
Jul 19 '05 #1
2 1682
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(s elf):
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.anc estors + [self.parent]
return []

A non-recursive variant:

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

Peter

Jul 19 '05 #2
Peter Otten wrote:
something like this didn't work for me:
<snip> But this will, I suppose:

@property
def ancestors(self) :
if self.parent:
return self.parent.anc estors + [self.parent]
return []

A non-recursive variant:

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


Indeed, both of these patterns suit my needs. Thanks very much for the
eye-opening insights.

Jeffrey
Jul 19 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
2318
by: Sandy Norton | last post by:
If we are going to be stuck with @decorators for 2.4, then how about using blocks and indentation to elminate repetition and increase readability: Example 1 --------- class Klass: def __init__(self, name):
24
2070
by: Steven Bethard | last post by:
I think one of the biggest reasons we're having such problems coming to any agreement on decorator syntax is that each proposal makes a number of syntax decisions, not just one. For decorators, I see the following decisions that must be made: 1) Indicator Proposals differ on how some sort of indicator of "decoratorhood" is use. These include: * none (e.g. just the list, as in the "list-after-def" suggestion) * the '@' character
11
1636
by: Ville Vainio | last post by:
It might just be that @decorator might not be all that bad. When you look at code that uses it it's not that ugly after all. A lot of the furor about this is probably because it happened so quicly. The situation might have been different if we had seen a pronouncement a week before, in the vein of "I have chosen this syntax - it will go in to the next alpha". My chief worry was throwing away one of the few unused ascii symbols, but if...
37
2610
by: Bengt Richter | last post by:
ISTM that @limited_expression_producing_function @another def func(): pass is syntactic sugar for creating a hidden list of functions. (Using '|' in place of '@' doesn't change the picture much (except for people whose tools depend on '@' ;-)). I.e., (not having the source or time to delve) the apparent semantics of the above is something roughly like
7
1589
by: Steven Bethard | last post by:
So here's the state of the decorator debate as I see it: *** Location GvR pretty strongly wants decorators before the function: http://mail.python.org/pipermail/python-dev/2004-August/047112.html http://mail.python.org/pipermail/python-dev/2004-August/047279.html
41
2880
by: John Marshall | last post by:
How about the following, which I am almost positive has not been suggested: ----- class Klass: def __init__(self, name): self.name = name deco meth0: staticmethod def meth0(x):
22
2242
by: Ron_Adam | last post by:
Hi, Thanks again for all the helping me understand the details of decorators. I put together a class to create decorators that could make them a lot easier to use. It still has a few glitches in it that needs to be addressed. (1) The test for the 'function' object needs to not test for a string but an object type instead.
19
2288
by: Kay Schluehr | last post by:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
0
1262
by: Miguel Perez | last post by:
Please critique this tail call optimizing decorator I've written. I've tried to fix the pitfalls of other proposed decorators, and the result is this one that supports mutual recursion, does not use exceptions, stack inspection or any implementation-dependent hack, and is pretty short and fast - the fastest out of the ones I could find and try. In fact, in tail-recursive environments I tested the impact of using the decorator is difficult...
0
9683
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9529
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10457
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10013
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9054
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6792
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5443
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2927
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.