Concise idiom to initialize dictionaries
Steven Bethard
steven.bethard at gmail.com
Thu Nov 11 15:30:18 EST 2004
Caleb Hattingh <caleb1 <at> telkomsa.net> writes:
>
> For interest sake, how would such a thing look with new-style classes? My
> (likely misinformed) impression is that __getattr__ for example, doesn't
> behave in quite the same way?
Just the same[1] =)
>>> class AllDicts(object):
... def __getattr__(self, name):
... d = {}
... setattr(self, name, d)
... return d
... def __repr__(self):
... items = self.__dict__.items()
... items.sort()
... return '\n'.join(['%s -> %r' % item for item in items])
...
>>> ad = AllDicts()
>>> ad.a[1] = 99
>>> ad.b[2] = 42
>>> ad.b[3] = 11
>>> ad
a -> {1: 99}
b -> {2: 42, 3: 11}
>>>
I believe that __getattr__ works just the same (but to check for yourself, see
http://docs.python.org/ref/attribute-access.html). I think what you're thinking
of is __getattribute__ which new-style classes offer *in addition* to
__getattr__. While __getattr__ is called only if an attribute is not found,
__getattribute__ is called unconditionally for every attribute access.
Steve
[1] modulo my preference for list comprehensions/generator expressions instead
of map
More information about the Python-list
mailing list