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

Ethan Furman ethan at stoneleaf.us
Mon Jan 30 20:25:12 CET 2012


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.

~Ethan~



More information about the Python-ideas mailing list