Concise idiom to initialize dictionaries

Caleb Hattingh caleb1 at telkomsa.net
Thu Nov 11 22:18:14 EST 2004


Peter, respect :)

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?

thx
Caleb


On Tue, 09 Nov 2004 20:12:15 +0100, Peter Otten <__peter__ at web.de> wrote:

>
> Here is a bunch of dictionaries that spring into existence by what is
> believed to be magic :-)
>
>>>> class AllDicts:
> ...     def __getattr__(self, name):
> ...             d = {}
> ...             setattr(self, name, d)
> ...             return d
> ..     def __repr__(self):
> ...             items = self.__dict__.items()
> ...             items.sort()
> ...             return "\n".join(map("%s -> %r".__mod__, items))
> ...
>>>> ad = AllDicts()
>>>> ad.a[1] = 99
>>>> ad.b[2] = 42
>>>> ad.b[3] = 11
>>>> ad
> a -> {1: 99}
> b -> {2: 42, 3: 11}
>
> Peter
>




More information about the Python-list mailing list