473,756 Members | 4,165 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

__getattr__ and recursion ?

hello,

I tried to find an easy way to add properties (attributes) to a number
of different components.
So I wrote a class, from which all these components are derived.
By trial and error I created the code below, which now works, but
there is one thing I don't understand:
in the line indicated with "<<== 1" I'm not allowed to use

for item in self.extra_gett ers :

because it will result in an infinite recursion.
But in the line indicated with "<<== 2" , I am allowed ...
.... why is this allowed ??

thanks,
Stef Mientki
# *************** *************** *************** *************** ***********
# *************** *************** *************** *************** ***********
class _add_attribs ( object ) :
def __init__ ( self ) :
self.extra_sett ers = {}
self.extra_gett ers = {}

def _add_attrib ( self, text, setter = None, getter = None ) :
if setter :
self.extra_sett ers [ text ] = setter
if getter :
self.extra_gett ers [ text ] = getter

# *************** *************** *************** ************
# always called instead of the normal mechanism
# *************** *************** *************** ************
def __setattr__ ( self, attr, value ) :
for item in self.extra_sett ers :
if item == attr :
self.extra_sett ers [ item ] ( value )
break
else :
self.__dict__[attr] = value

# *************** *************** *************** ************
# only called when not found with the normal mechanism
# *************** *************** *************** ************
def __getattr__ ( self, attr ) :
try :
for item in self.__dict__['extra_getters'] : <<== 1
if item == attr :
return self.extra_gett ers [ item ] ( ) <<== 2
except :
return []
# *************** *************** *************** *************** ***********

Jun 27 '08 #1
2 2668
Stef Mientki wrote:
hello,

I tried to find an easy way to add properties (attributes) to a number
of different components.
So I wrote a class, from which all these components are derived.
By trial and error I created the code below, which now works, but
there is one thing I don't understand:
in the line indicated with "<<== 1" I'm not allowed to use

for item in self.extra_gett ers :

because it will result in an infinite recursion.
But in the line indicated with "<<== 2" , I am allowed ...
... why is this allowed ??
When the instance is created

self.extra_sett ers = {}

in the __init__() method triggers

self.__setattr_ _("extra_setter s", {})

which executes

for item in self.extra_sett ers:
# ...

in the __setattr__() method. Because at that point there is no extra_setters
attribute

self.__dict__["extra_sett ers"]

fails and self.__getattr_ _("extra_setter s") is used as a fallback. Now as
__getattr__() contains a self.extra_gett ers attribute access and that
attribute doesn't exist either this again triggers

self.__getattr_ _("extra_getter s") -- ad infinitum.

By the way, looping over a dictionary destroys its key advantage, O(1)
lookup. Use

# untested
if attr in self.extra_sett ers:
self.extra_sett ers[attr](value)
else:
self.__dict__[attr] = value

and something similar in __getattr__().

Peter
>
thanks,
Stef Mientki
# *************** *************** *************** *************** ***********
# *************** *************** *************** *************** ***********
class _add_attribs ( object ) :
def __init__ ( self ) :
self.extra_sett ers = {}
self.extra_gett ers = {}

def _add_attrib ( self, text, setter = None, getter = None ) :
if setter :
self.extra_sett ers [ text ] = setter
if getter :
self.extra_gett ers [ text ] = getter

# *************** *************** *************** ************
# always called instead of the normal mechanism
# *************** *************** *************** ************
def __setattr__ ( self, attr, value ) :
for item in self.extra_sett ers :
if item == attr :
self.extra_sett ers [ item ] ( value )
break
else :
self.__dict__[attr] = value

# *************** *************** *************** ************
# only called when not found with the normal mechanism
# *************** *************** *************** ************
def __getattr__ ( self, attr ) :
try :
for item in self.__dict__['extra_getters'] : <<== 1
if item == attr :
return self.extra_gett ers [ item ] ( ) <<== 2
except :
return []
# *************** *************** *************** *************** ***********
Jun 27 '08 #2
thanks Peter,

for your perfect explanation, and
By the way, looping over a dictionary destroys its key advantage, O(1)
lookup. Use

# untested
if attr in self.extra_sett ers:
self.extra_sett ers[attr](value)
else:
self.__dict__[attr] = value

and something similar in __getattr__().

yes, that's probably much better, have to get used to this Python behavior,
thanks,

cheers,
Stef

Jun 27 '08 #3

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

Similar topics

3
3360
by: Greg Brunet | last post by:
In adding the ability to refer to field values using dbfFile.field notation, I learned how to use __getattr__ and __setattr__ . After some trial and error, I got it working. But as part of my trials, I added some print statements to debug stuff. The ones I added to __setattr__ work as expected, but the one in __getattr__ seems to get called just under 1000 times for every __getattr__ call! Something is obviously not right here - but...
1
1415
by: Holger Joukl | last post by:
Hi there, please excuse my rather lengthy post. With introduction of the new style classes, something seems to have changed for __getattr__ hooks, even for classic classes: getattr.py: class A: # classic! def __getattr__(self, attr): print "-->A.__getattr__"
0
6602
by: Gigi | last post by:
Hi, In the Python documentation regarding __getattribute__ (more attribute access for new style classes) it is mentioned that if __getattribute__ is defined __getattr__ will never be called (unless called explicitely). Here is the exact citation: """ The following methods only apply to new-style classes. __getattribute__( self, name)
13
3496
by: Pelmen | last post by:
How can I get rid of recursive call __getattr__ inside this method, if i need to use method or property of the class?
6
4507
by: Erik Johnson | last post by:
Maybe I just don't know the right special function, but what I am wanting to do is write something akin to a __getattr__ function so that when you try to call an object method that doesn't exist, it get's intercepted *along with it's argument*, in the same manner as __getattr__ intercepts attributes references for attributes that don't exist. This doesn't quite work: >>> class Foo:
7
1617
by: bearophileHUGS | last post by:
I have tried this, with Psyco it segfaults, and with Python 2.5 (on Win) hangs the interpreter, is it possible to improve the situation? class T(object): def __getattr__(self, x): dir(self) #import psyco #psyco.full() T().method() (Probably dir calls __getattr__).
5
2410
by: glomde | last post by:
Hi, I tried to write a decorator for that should be for methods but for some reasons it doens seem to work when you try to do it on the __getattr__ method in a class. Could anybody give some hints why this is? Example: class decoratorTest(object):
4
3943
by: Enrico | last post by:
Hi there, I have the following situation (I tryed to minimize the code to concentrate on the issue): def __getattr__(self, name): print 'A.__getattr__' if name == 'a': return 1 raise AttributeError('%s not found in A' % name) def __getattr__(self, name):
7
1710
by: =?UTF-8?Q?Alexandru_Mo=C8=99oi?= | last post by:
i'm facing the following problem: class Base(object): def __getattr__(self, attr): return lambda x: attr + '_' + x def dec(callable): return lambda *args: 'dec_' + callable(*args) class Derived(Base): what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have
0
9487
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
10069
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
9884
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
9735
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
8736
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...
1
7285
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6556
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();...
2
3395
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2697
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.