A class for C-like structuures in Python

Alex Martelli alex at magenta.com
Wed Aug 9 08:58:48 EDT 2000


"Thomas Gagne" <tgagne at ix.netcom.com> wrote in message
news:399145B4.B3771618 at ix.netcom.com...
> Whoops!!
>
> When I run my test program, I get a tracback that looks like __getattr__
calls
> __checkname which calls __getattr__ which calls __checkname.... but I
don't
> see it in the code.
    [snip]
> def __getattr__(self, name):
> self.__checkname(name)
> return self.members[name]
>
> def __setattr__(self, name, value):
> self.__checkname(name)
> self.members[name] = value
> return value

Sorry, my fault, I should have thought of it.  With these definitions you
can
never get anything into the instance's actual dictionary via "normal"
binding:
e.g., when __init__ does
    self.members = whatever
then __setattr__ gets called (because 'members' is not in self.__dict__),
then it calls __checkname which tries to read self.members -- but again
that's not in the __dict__, so __getattr__ is called -- which calls
__checkname, etc, etc.

Solution: in __init__, INSTEAD OF
    self.members = whatever
etc, do:
    self.__dict__['members'] = whatever
which DOES insert the reference right into the dictionary, so that after
this requests for self.members will bypass the __getattr__, and everybody
will live happily ever after.

I apologize for not mentioning this in my earlier post!


Alex






More information about the Python-list mailing list