Dictionaries and dot notation

Daniel Nogradi nogradi at gmail.com
Sun Apr 22 12:02:00 EDT 2007


> > This may be pretty obvious for most of you:
> >
> > When I have an object (an instance of a class "Foo") I can access
> > attributes via dot notation:
> >
> >         aFoo.bar
> >
> > however when I have a dictionary
> >
> >         aDict = {"bar":"something"}
> >
> > I have to write
> >
> >         aDict["bar"]
> >
> > 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.

Daniel



More information about the Python-list mailing list