Dictionaries and dot notation

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Apr 23 22:45:26 CEST 2007


Martin Drautzburg a écrit :
> Daniel Nogradi wrote:
> 
> 
> 
>>>>What if I want to create a datastructure that can be used in dot
>>>>notation without having to create a class, i.e. because those
>>>>objects have no behavior at all?
>>>
>>>A class inheriting from dict and implementing __getattr__ and
>>>__setattr__ should do the trick...
>>
>>
>>It can do the trick but one has to be careful with attributes that are
>>used by dict such as update, keys, pop, etc. Actually it's noted in a
>>comment at
>>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668 why the
>>whole idea (attribute access of dictionaries) is a bad idea and I tend
>>to agree.
> 
> 
> Oh thank you. So all I have to do is have my object's class implement
> __setattr__ and __getattr__, or derive it from a class that does so?
> And I could save my "attributes" anywhere within my instance variables.
> So I could even add a dictionary whose name does not conflict with what
> python uses and whose key/value pairs hold the attributes I want to
> access with dot notation and delegate all the python attributes to
> their native positions? Oh I see, thats tricky. I still need to be
> aware of the builtin stuff one way or the other.

Yeps. FWIW, Daniel is right to raise a warning here, and I should have 
think one more minute before posting - since in fact in this case you 
don't care about dict-like behaviour.


> Interesting.



More information about the Python-list mailing list