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

Georg Brandl g.brandl at gmx.net
Tue Jan 31 08:10:03 CET 2012


Am 30.01.2012 20:23, schrieb Ethan Furman:
> Antoine Pitrou wrote:
>> On Mon, 30 Jan 2012 12:49:54 -0600
>> Massimo Di Pierro
>> <massimo.dipierro at gmail.com> wrote:
>>> Trying to make sure I understand where we disagree and perhaps explain my problem better. For me this has very little to do with dictionaries.
>> 
>>> 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?
>> 
>> Yes. You don't need both kinds of accesses.
> 
> Sure you do -- as soon as 'something' can be passed in via a variable:
> 
> def some_func(name):
>      print(d.name)  # uh, no
>      print(d[name]) # okay, this works

If anything, the d.[name] (short for getattr(d, name)) proposal should be
reconsidered.  But IIRC it was concluded when discussed last time that the
syntax is too hard to quickly distinguish from item access, and a better
one couldn't be found.

Georg




More information about the Python-ideas mailing list