[Python-ideas] Shorthand syntax for get/set/delattr (was Re: Dict-like object with property access)

Carl M. Johnson cmjohnson.mailinglist at gmail.com
Sun Feb 5 14:25:04 CET 2012


On Feb 5, 2012, at 2:58 AM, yoav glazner wrote:

> 
> 
> On Sun, Feb 5, 2012 at 12:46 PM, Serhiy Storchaka <storchaka at gmail.com> wrote:
> 05.02.12 02:20, Nick Coghlan написав(ла):
> It would be a *lot* cleaner if we could just use a normal assignment
> statement instead of builtin functions to perform the name binding. As
> it turns out, for ordinary instances, we can already do exactly that:
> 
>     for attr in "attr1 attr2 attr3".split():
>         vars(x)[attr] = vars(y)[attr]
> 
> In short, I think proposals for dedicated syntax for dynamic attribute
> access are misguided - instead, such efforts should go into enhancing
> vars() to return objects that support *full* dict-style access to the
> underlying object's attribute namespace (with descriptor protocol
> support and all).
> 
> One-liner "def vars(v): return v.__dict__"?
> 
> This does't work for properties:

It's not that hard to make something that basically works with properties:


>>> class vars2:
...     def __init__(self, obj):
...         self.obj = obj
...     
...     def __getitem__(self, key):
...         return getattr(self.obj, key)
...     
...     def __setitem__(self, key, value):
...         setattr(self.obj, key, value)
...     
...     def __delitem__(self, key):
...         delattr(self.obj, key)
... 
>>> class P:
...     def __init__(self):
...         self.value = 1
...     
...     @property
...     def pop(self): return 'corn'
...     
...     @property
...     def double(self):
...         return self.value * 2
...     
...     @double.setter
...     def double(self, value):
...         self.value = value/2
... 
>>> p = P()
>>> p.pop
'corn'
>>> v  = vars2(p)
>>> v['pop']
'corn'
>>> v['value']
1
>>> v['double']
2
>>> v['double'] = 4
>>> v['value']
2.0
>>> v['double']
4.0

In a real module, you'd probably want to be more thorough about emulating a __dict__ dictionary though by adding item() and keys() etc.


More information about the Python-ideas mailing list