dictionary and __getattr__

Alex Martelli aleax at aleax.it
Thu Sep 6 10:46:10 EDT 2001


"Heiko Wundram" <heikowu at ceosg.de> wrote in message
news:mailman.999774247.7475.python-list at python.org...
    ...
> # Works with Python 2.2a2.

Doesn't work, because of the usual __setattr__ problem:

> from __future__ import generators
>
> class AttributeDictionary:
>
>     def __init__(self):
>         self.dict = {}

This calls self.__setattr__('dict',{})
    [snip]
>     def __setattr__(self, key, value):
>         self.dict[key] = value

...which in turn calls self.__getattr__('dict') first,
etc, etc.

When a class has __setattr__, remember it's going to
be called for EVERY attribute-setting.  So, in this
case, __init__ must start with
    self.__dict__['dict'] = {}

Things are slightly different in 2.2: __getattr__
also becomes called-everytime, you can define the
slots explicitly, etc, but not for classic classes
(only for those that extend list, dictionary, or
object, I believe).


Alex






More information about the Python-list mailing list