[Python-ideas] Dict-like object with property access

Oleg Broytman phd at phdru.name
Mon Jan 30 21:06:32 CET 2012


On Mon, Jan 30, 2012 at 11:25:12AM -0800, Ethan Furman wrote:
> Oleg Broytman wrote:
> >On Mon, Jan 30, 2012 at 12:49:54PM -0600, Massimo Di Pierro wrote:
> >>STEP 2) We can now overload the [] to make the dynamic attributes accessible in an alternative syntax:
> >>
> >>    class Dummy(object):
> >>          def __getitem__(self,key): return getattr(self,key)
> >>          def __setitem__(self,key,value): return setattr(self,key,value)
> >>    d = Dummy()
> >>    d.something = 5
> >>    d['something'] = 5
> >>    print d.something
> >>    print d['something']
> >>
> >>STEP 3) Is anybody calling this un-pythonic?
> >
> >   I do. The object has two different interfaces for the same values and
> >that's IMO unpythonic. The Zen says
> >
> >   "There should be one-- and preferably only one --obvious way to do it."
> 
> Indeed.
> 
> When you have the attribute name stored in a variable, then the one
> obvious way is [] access.
> 
> When you already know the attribute name, the one obvious way is . access.

   Sure, for attributes. But a dict contents ain't attributes, it's
(key => value) mapping. So for a dict, getitem interface give access to
dict's content, while getattr interface give access to dict's services -
all those .keys(), .items(), .values(), .clear(), .update() et al.

Oleg.
-- 
     Oleg Broytman            http://phdru.name/            phd at phdru.name
           Programmers don't die, they just GOSUB without RETURN.



More information about the Python-ideas mailing list