[Python-Dev] Issue 643841: Including a new-style proxy base class in 2.6/3.0

Nick Coghlan ncoghlan at gmail.com
Tue May 27 15:32:38 CEST 2008


Michael Foord wrote:
> Nick Coghlan wrote:
>> - ProxyMixin correctly delegates in-place assignment operations via 
>> the __i*__ methods (note however that using in-place assignment will 
>> remove the proxy wrapper, just as it does for weakref.proxy)
> 
> Couldn't in place operations wrap the return value with a proxy?

They could, but I tried to copy as much behaviour as possible from 
weakref.proxy which loses the proxy wrapper when you do an in-place 
operation:

 >>> from weakref import proxy as p
 >>> class MyInt(int): pass
...
 >>> x = MyInt(1)
 >>> px = p(x)
 >>> px
<weakproxy at 0xb768f11c to MyInt at 0xb768d86c>
 >>> px += 1
 >>> px
2

 >>> class MyList(list): pass
...
 >>> y = MyList([])
 >>> py = p(y)
 >>> py
<weakproxy at 0xb768f16c to MyList at 0xb768f0f4>
 >>> py += []
 >>> py
[]

That said, it wouldn't be hard (and might make more sense) to redefine 
the proxied in-place operations along the following lines:

# See tracker item for _deref/_unwrap definitions
def __iadd__(self, other):
     target = _deref(self)
     result = target + _unwrap(other)
     if result is target:
         # Mutated in-place, keep same proxy
         result = self
     else:
         # Returned a different object, make a new proxy
         result = type(self)(result)
     return result

However, if we did something like that, I'd prefer to see the 
weakref.proxy implementation change to provide similar semantics.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list