Dictionaries and dot notation

Antoon Pardon apardon at forel.vub.ac.be
Mon Apr 23 10:18:56 CEST 2007

On 2007-04-22, Martin Drautzburg <Martin.Drautzburg at web.de> wrote:
> 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.

Maybe you can do the opposite and create a class that implements
__getitem__ and __setitem__ in function of attribute access.

The following is an example:

class Rec(object):
     def __init__(__, **kwargs):
         for key,value in kwargs.items():
             setattr(__, key, value)

     def __getitem__(self, key):
         return getattr(self, key)

     def __setitem__ (self, key, val):
         setattr(self, key, val)

rec = Rec(a=1)

print rec.a
print rec["a"]

rec.b = 2
print rec["b"]

rec["c"] = 3
print rec.c

Antoon Pardon

More information about the Python-list mailing list