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

Paul Moore p.f.moore at gmail.com
Sun Feb 5 22:18:09 CET 2012

On 5 February 2012 20:45, Simon Sapin <simon.sapin at kozea.fr> wrote:
> +1 on extending vars(). I like this idea much more than adding syntax.
> In this case, proxy(a).key() would be based on dir(a) (or something similar)
> and have the same (documented) limitations. I think this is acceptable, and
> the proxy object is still useful.

vars() and dir() do very different things:

>>> class A:
...   pass
>>> a = A()
>>> a.a = 1
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__h
ash__', '__init__', '__le__', '__lt__', '__module__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '_
_setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a']
>>> vars(a)
{'a': 1}

In my view, following the spec of vars() is far more useful and
matches better the original requirement, which was to simulate
javascript's index/attribute duality. Methods (and even more so
special methods) don't really fit in here.

I'd argue for the definition:

proxy(obj)['a'] <=> obj.a
proxy(obj)['a' = val] <=> obj.a = val
del proxy(obj)['a'] <=> del obj.a
'a' in proxy(obj) <=> hasattr(obj, 'a')
proxy(obj).keys() <=> vars(obj).keys()
len(proxy(obj)) <=> len(vars(obj))

In other words, indexing defers to getattr/setattr/delattr,
containment uses hasattr, but anything else goes via vars. In terms of
ABCs, Sized/Iterable behaviour comes from vars(),
Container/Mapping/MutableMapping behaviour comes from

It's mildly inconsistent for objects which implement their own
attribute access, but those aren't the key use case, and the behaviour
is well defined even for those.


More information about the Python-ideas mailing list