[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 16:16:40 CET 2012


2012/2/5 Serhiy Storchaka <storchaka at gmail.com>:
> 05.02.12 15:25, Carl M. Johnson написав(ла):
>> On Feb 5, 2012, at 2:58 AM, yoav glazner wrote:
>>> This does't work for properties:
>> It's not that hard to make something that basically works with properties:
>
> del v['pop']
> AttributeError: P instance has no attribute 'pop'
>
>
>> In a real module, you'd probably want to be more thorough about emulating a __dict__ dictionary though by adding item() and keys() etc.
>
> It's impossible in general.
>
> class A:
>    def __getattr__(self, name):
>        return len(name)


>>> class proxy:
...   def __init__(self, orig):
...     self._orig = orig
...   def __getitem__(self, attr):
...     return getattr(self._orig,attr)
...
>>> class A:
...   def __getattr__(self, name):
...     return len(name)
...
>>> a = A()
>>> proxy(a)['hello']
5
>>>

Extending the proxy class to include setting, deleting, and various
corner cases, is left as an exercise for the reader :-)

Paul



More information about the Python-ideas mailing list