Dictionaries and dot notation

Martin Drautzburg Martin.Drautzburg at web.de
Sun Apr 22 14:36:48 EDT 2007


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.

Interesting.



More information about the Python-list mailing list