problems with __getattr__ & __setattr__

Robert Vollmert rvollmert at gmx.net
Tue Nov 16 15:47:04 EST 1999


Hi,

On Tue, Nov 16, 1999 at 02:24:08PM -0500, ScherBi at bam.com wrote:
> I am having trouble using __getattr__ and __setattr__ in some classes.  I've
> boiled it down to the code below.
> It dumps core under 1.5.2 on Linux or WinNT.
> 
> I think maybe it's looping, if so, how does one go about doing this? 
> (I'm assuming it's clear enough what I'm trying to do.)
> 
> If I comment out the __gettattr__ operation, it doesn't dump core.  Instead
> I get an AttributeError: eggs raised at the 'self.eggs[key] = value' call in
> __setattr__.  This is what leads me to belive there's something circular
> going on here.

in __init__, 'self.eggs = {}' calls __setattr__, where the assignment
to self.eggs[key] calls __getattr__(self, 'eggs'), as self.eggs
doesn't exist yet. This is also why you get an attribute error if
__getattr__ is commented out.

In __getattr__, the reference to self.eggs causes __getattr__ to be
called again. This continues until infinity (well, almost ;-). 

To fix this, you would probably best use self.__dict__['eggs'] instead
of self.eggs, as this skips __getattr__/__setattr__ calls.

Hope this is correct and helps,
Robert

> -------------------------------------------------------------
> 
> class spam:
> 
>     def __init__(self):
>         self.eggs = {}
>     
>     def __getattr__(self, key):
>         try:
>             return self.eggs[key]
>         except:
>             raise
>         
>     def __setattr__(self, key, value):
>         try:
>             self.eggs[key] = value
>             return 0
>         except:
>             raise
> 
> 
> 
> if __name__ == '__main__':
> 
>     s = spam()
>     print 'instance of spam created.' 
> 
> ------------------------------------------------------------------


-- 
Robert Vollmert                                      rvollmert at gmx.net




More information about the Python-list mailing list