dict!ident as equivalent of dict["ident"]

Alexander Kozlovsky alexander.kozlovsky at gmail.com
Sun May 21 10:31:34 EDT 2006


Roy Smith wrote:
> Define a class (perhaps a subclass of dict, if you like)
> with a __getattr__ method.  Then you can just do
> 
> foo.bar.baz.x = y
> 
> with no changes needed to the language.

I think, your solution is very error-prone. If such enhanced
dictionary contains "keys" key, what is meaning of d.keys?
Is it bound method or dictionary item? After you introduce
such dictionary, you cannot add any new method for it, because
it may destroy user code, if acciddent name clashing take place.

Consider SQLTable class, which have "name" attribute, and
bunch of dynamically created named columns. With __getattr__
method you can use SQLTable.column_1 syntax for column access,
but what if same column have name "name"? It may be very
psychologically inconvenient for user of such class to use
same foo.bar syntax for two different purposes.

In most real cases it is important to distinguish between
two different namespaces - "members" namespace with methods
properties etc., and "items" namespace with truly dynamic
content. In todays Python such distinction accomplished
with two different methods - __getattr(ibute)__ and __getitem__.

It is not possible to successfully use only __getattr__
to serve two different purposes. Hense I suggest use
__getitem__ for its direct purpose, and only add some
syntactic sugar for it

Dan Sommers wrote:
> Take a look at the "Bunch" recipe in the Python Cookbook:
> 
>     http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308

This recipe is what is stated in its name - "collector
of a bunch of named stuff". It is not suitable for
elaborate classes with many methods (such as SQLTable),
for above mentioned reason - name cluttering between
methods, properties and dynamic content.


-- 
Best regards,
 Alexander                  mailto:alexander.kozlovsky at gmail.com




More information about the Python-list mailing list