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

Terry Reedy tjreedy at udel.edu
Mon Jan 30 22:17:24 CET 2012

On 1/30/2012 1:49 PM, Massimo Di Pierro wrote:
> Trying to make sure I understand where we disagree...
>      class Dummy(object): pass
>      d = Dummy()
>      d.something = 5
>      print d.something
> Is anybody calling this un-pythonic?

I already suggested that that is the way to make a pure *name* to data 
mapping object. If you want a default data object, add your corrected 
    def __getattr__(self,key): return self.__dict__.get(key,None)
To make Dummy instances key iterable like dicts, add
	def __iter__(self): return iter(self.__dict__)
If you prefer to iterate by name-object pairs:
	def __iter__(self): return iter(self.__dict__.items())
One could define a few other special methods, like __eq__, to tie into 
other syntax.

> 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)

> Is anybody calling this un-pythonic?

Guido already did, insofar as he defines 'pythonic'. Anyway, skip that 
word. This is where many of us 'disagree'. This design redefines Dummy 
as a *string* to data mapping object. You add a second access method 
that makes the first access method only partial. To me, it is a 
conceptually crazy object. And it gets worse when you try to make it a 
dict, with some names now reserved for methods. Dicts, lists, and tuples 
have a clean separation between contents, accessed by subscript, and 
methods to work on contents, accessed as attributes. Many of us consider 
that a virtue and a feature.

Terry Jan Reedy

More information about the Python-ideas mailing list