[Python-ideas] Dict-like object with property access (original) (raw)
Terry Reedy tjreedy at udel.edu
Mon Jan 30 22:17:24 CET 2012
- Previous message: [Python-ideas] Dict-like object with property access
- Next message: [Python-ideas] Dict-like object with property access
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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 method: 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
- Previous message: [Python-ideas] Dict-like object with property access
- Next message: [Python-ideas] Dict-like object with property access
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]