You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
There are many dunder methods documented here but are missing in ObjectProxy. Some of them like __call__ is defined in classes inheriting ObjectProxy. But for the sake of reusability of ObjectProxy, they should also be defined in it. Also, there are dunder methods like __next__ that are not even defined in inheriting classes. All of them should be defined in ObjectProxy.
Concerning __iter__, it is arguable that it was a mistake to add it to ObjectProxy in the first place as it has broken some code where people change behaviour based on a check of hasattr(obj, "__iter__"). That is, this check would always return True even though iter() would fail and raise an AttributeError. So in hindsight it perhaps shouldn't have been added, even if the hasattr check is sort of an anti Python and people should just capture errors when doing iteration itself.
As to __call__ is was never added because there callable() always existed for checking if something was callable and was clear that adding __call__ in base object proxy would cause issues straight away since people relied on callable(). That people were relying on hasattr(obj, "__iter__") was not so obvious.
Because of the issues with __iter__, this is why the asynchronous versions were never added later when that feature was added to Python.
As to __next__, what is the specific use case since __iter__ would call the __iter__ of the wrapped object and so the returned object which provides __next__ would not be a proxy object. Thus I don't see a direct reason why __next__ should appear in ObjectProxy as a default.
If you are overriding __iter__ on a custom object proxy to wrap the result when iter() is called, then you are already dealing with a mess of custom object proxies and so should be using such a custom object proxy to override __next__.
As to the statement that "there are many dunder methods documented but are missing in ObjectProxy", they would fall into two cases. The first is that they didn't exist in older Python versions when wrapt was first written. The second is that it isn't appropriate for them to be added on an object proxy, or at least not as default behaviour. In other words, would be more appropriate to add them in a custom object proxy.
So can you provide some example use case of what you are trying to do where you need __next__ to be proxied.
As to other dunder methods, list those you believe should be added by default on object proxy and provide specific examples so can understand why. In some cases where I learn of new dunder methods added in Python 3 they have been added, but only when asked and it makes sense to add them. I don't troll through each Python release looking for new dunder methods.
In order to solve problems of hasattr(obj, "__iter__") and callable(obj) you can define a function generating a ObjectProxy and before instantiating it, modify it depending on the needs of obj. Example for __call__:
defobject_proxy(wrapped):
classObjectProxy(with_metaclass(_ObjectProxyMetaType)): # type: ignore[misc]__slots__="__wrapped__"def__init__(self, wrapped):
object.__setattr__(self, "__wrapped__", wrapped)
# Python 3.2+ has the __qualname__ attribute, but it does not# allow it to be overridden using a property and it must instead# be an actual string object instead.try:
object.__setattr__(self, "__qualname__", wrapped.__qualname__)
exceptAttributeError:
pass# Python 3.10 onwards also does not allow itself to be overridden# using a property and it must instead be set explicitly.try:
object.__setattr__(self, "__annotations__", wrapped.__annotations__)
exceptAttributeError:
passdef__self_setattr__(self, name, value):
object.__setattr__(self, name, value)
@propertydef__name__(self):
returnself.__wrapped__.__name__@__name__.setterdef__name__(self, value):
self.__wrapped__.__name__=value@propertydef__class__(self):
returnself.__wrapped__.__class__@__class__.setterdef__class__(self, value):
self.__wrapped__.__class__=valuedef__dir__(self):
returndir(self.__wrapped__)
def__str__(self):
returnstr(self.__wrapped__)
def__bytes__(self):
returnbytes(self.__wrapped__)
def__repr__(self):
returnf"<{type(self).__name__} at 0x{id(self):x} for {type(self.__wrapped__).__name__} at 0x{id(self.__wrapped__):x}>"def__format__(self, format_spec):
returnformat(self.__wrapped__, format_spec)
def__reversed__(self):
returnreversed(self.__wrapped__)
def__round__(self, ndigits=None):
returnround(self.__wrapped__, ndigits)
def__mro_entries__(self, bases):
return (self.__wrapped__,)
def__lt__(self, other):
returnself.__wrapped__<otherdef__le__(self, other):
returnself.__wrapped__<=otherdef__eq__(self, other):
returnself.__wrapped__==otherdef__ne__(self, other):
returnself.__wrapped__!=otherdef__gt__(self, other):
returnself.__wrapped__>otherdef__ge__(self, other):
returnself.__wrapped__>=otherdef__hash__(self):
returnhash(self.__wrapped__)
def__nonzero__(self):
returnbool(self.__wrapped__)
def__bool__(self):
returnbool(self.__wrapped__)
def__setattr__(self, name, value):
ifname.startswith("_self_"):
object.__setattr__(self, name, value)
elifname=="__wrapped__":
object.__setattr__(self, name, value)
try:
object.__delattr__(self, "__qualname__")
exceptAttributeError:
passtry:
object.__setattr__(self, "__qualname__", value.__qualname__)
exceptAttributeError:
passtry:
object.__delattr__(self, "__annotations__")
exceptAttributeError:
passtry:
object.__setattr__(self, "__annotations__", value.__annotations__)
exceptAttributeError:
passelifname=="__qualname__":
setattr(self.__wrapped__, name, value)
object.__setattr__(self, name, value)
elifname=="__annotations__":
setattr(self.__wrapped__, name, value)
object.__setattr__(self, name, value)
elifhasattr(type(self), name):
object.__setattr__(self, name, value)
else:
setattr(self.__wrapped__, name, value)
def__getattr__(self, name):
# If we are being to lookup '__wrapped__' then the# '__init__()' method cannot have been called.ifname=="__wrapped__":
raiseWrapperNotInitializedError("wrapper has not been initialised")
returngetattr(self.__wrapped__, name)
def__delattr__(self, name):
ifname.startswith("_self_"):
object.__delattr__(self, name)
elifname=="__wrapped__":
raiseTypeError("__wrapped__ must be an object")
elifname=="__qualname__":
object.__delattr__(self, name)
delattr(self.__wrapped__, name)
elifhasattr(type(self), name):
object.__delattr__(self, name)
else:
delattr(self.__wrapped__, name)
def__add__(self, other):
returnself.__wrapped__+otherdef__sub__(self, other):
returnself.__wrapped__-otherdef__mul__(self, other):
returnself.__wrapped__*otherdef__truediv__(self, other):
returnoperator.truediv(self.__wrapped__, other)
def__floordiv__(self, other):
returnself.__wrapped__//otherdef__mod__(self, other):
returnself.__wrapped__%otherdef__divmod__(self, other):
returndivmod(self.__wrapped__, other)
def__pow__(self, other, *args):
returnpow(self.__wrapped__, other, *args)
def__lshift__(self, other):
returnself.__wrapped__<<otherdef__rshift__(self, other):
returnself.__wrapped__>>otherdef__and__(self, other):
returnself.__wrapped__&otherdef__xor__(self, other):
returnself.__wrapped__^otherdef__or__(self, other):
returnself.__wrapped__|otherdef__radd__(self, other):
returnother+self.__wrapped__def__rsub__(self, other):
returnother-self.__wrapped__def__rmul__(self, other):
returnother*self.__wrapped__def__rtruediv__(self, other):
returnoperator.truediv(other, self.__wrapped__)
def__rfloordiv__(self, other):
returnother//self.__wrapped__def__rmod__(self, other):
returnother%self.__wrapped__def__rdivmod__(self, other):
returndivmod(other, self.__wrapped__)
def__rpow__(self, other, *args):
returnpow(other, self.__wrapped__, *args)
def__rlshift__(self, other):
returnother<<self.__wrapped__def__rrshift__(self, other):
returnother>>self.__wrapped__def__rand__(self, other):
returnother&self.__wrapped__def__rxor__(self, other):
returnother^self.__wrapped__def__ror__(self, other):
returnother|self.__wrapped__def__iadd__(self, other):
self.__wrapped__+=otherreturnselfdef__isub__(self, other):
self.__wrapped__-=otherreturnselfdef__imul__(self, other):
self.__wrapped__*=otherreturnselfdef__itruediv__(self, other):
self.__wrapped__=operator.itruediv(self.__wrapped__, other)
returnselfdef__ifloordiv__(self, other):
self.__wrapped__//=otherreturnselfdef__imod__(self, other):
self.__wrapped__%=otherreturnselfdef__ipow__(self, other): # type: ignore[misc]self.__wrapped__**=otherreturnselfdef__ilshift__(self, other):
self.__wrapped__<<=otherreturnselfdef__irshift__(self, other):
self.__wrapped__>>=otherreturnselfdef__iand__(self, other):
self.__wrapped__&=otherreturnselfdef__ixor__(self, other):
self.__wrapped__^=otherreturnselfdef__ior__(self, other):
self.__wrapped__|=otherreturnselfdef__neg__(self):
return-self.__wrapped__def__pos__(self):
return+self.__wrapped__def__abs__(self):
returnabs(self.__wrapped__)
def__invert__(self):
return~self.__wrapped__def__int__(self):
returnint(self.__wrapped__)
def__float__(self):
returnfloat(self.__wrapped__)
def__complex__(self):
returncomplex(self.__wrapped__)
def__oct__(self):
returnoct(self.__wrapped__)
def__hex__(self):
returnhex(self.__wrapped__)
def__index__(self):
returnoperator.index(self.__wrapped__)
def__len__(self):
returnlen(self.__wrapped__)
def__contains__(self, value):
returnvalueinself.__wrapped__def__getitem__(self, key):
returnself.__wrapped__[key]
def__setitem__(self, key, value):
self.__wrapped__[key] =valuedef__delitem__(self, key):
delself.__wrapped__[key]
def__getslice__(self, i, j):
returnself.__wrapped__[i:j]
def__setslice__(self, i, j, value):
self.__wrapped__[i:j] =valuedef__delslice__(self, i, j):
delself.__wrapped__[i:j]
def__enter__(self):
returnself.__wrapped__.__enter__()
def__exit__(self, *args, **kwargs):
returnself.__wrapped__.__exit__(*args, **kwargs)
def__iter__(self):
returniter(self.__wrapped__)
def__copy__(self):
raiseNotImplementedError("object proxy must define __copy__()")
def__deepcopy__(self, memo):
raiseNotImplementedError("object proxy must define __deepcopy__()")
def__reduce__(self):
raiseNotImplementedError("object proxy must define __reduce__()")
def__reduce_ex__(self, protocol):
raiseNotImplementedError("object proxy must define __reduce_ex__()")
ifcallable(wrapped):
def__call__(self, *args, **kwargs):
returnself.__wrapped__(*args, **kwargs)
ObjectProxy.__call__=__call__returnObjectProxy(wrapped)
Usage example:
So for example, if inspect.isawaitable(obj) is the reason you didn't implement __await__, you can solve it the same way.
As to __next__, what is the specific use case
Proxying an iterator instead of a iterable:
As to other dunder methods, list those you believe should be added by default on object proxy
E.g There are __enter__ and __exit__ in ObjectProxy but their async versions are missing (__aenter__ and __aexit__). And if you decide to implement __next__, there is also __anext__. This is not the complete list. There are some other missing methods too.
You can do that inside of the __init__ method itself, but that technique is only of use for the pure Python implementation of ObjectProxy.
The pure Python implementation would rarely be used as it exists only as a fallback for when the C implementation isn't used for some reason.
In a C implementation of a Python object that sort of trick will not work because Python when it sees an object implemented in C, will only look in the tp_ slots of the C structure defining the type, and will ignore __iter__ and __call__ which are added as an attribute on the C object __dict__.
To be able to use the trick that works for the pure Python object implementation it would be necessary to change wrapt so that the existing C implementation of ObjectProxy is renamed to _ObjectProxy and then create a small ObjectProxy Python implementation shim that inherits from C based _ObjectProxy and in the Python implementation of the derived class __init__ then you could do it.
I will need to research though what the implications of doing this will be though on other dunder attributes which have weird rules such as __qualname__ and __annotations__, plus the meta class hacks. These may have to be replicated in that derived ObjectProxy for the C implementation as well as that in the C base class may no longer have the desired effect.
Although I expect it may be minimal enough that not a concern, adding the extra Python class deriving from C implementation may have extra overhead as a result.
Anyway, your response didn't answer the main question I put to you, which was the example you had where having __next__ as a default on ObjectProxy would be useful.
You can't do that inside __init__ because magic methods aren't automatically called when they are object attributes instead of class attributes. See this code:
This gives: TypeError: 'A' object is not callable
You also can't monkeypatch ObjectProxy inside __init__ because that change will be reflected on all ObjectProxy instances and it is possible that one instance should be callable and another shouldn't be. So that every ObjectProxy instance should have its own type.
your response didn't answer the main question I put to you
I don't have a real world example but i tried to answer you by giving an example of proxying an iterator. Isn't being unable to correctly proxy an iterator bad enough?
Lastly, you also didn't answer a question of mine. Why didn't you implement __aenter__ and __aexit__?
would not have desired effect since that would set __call__ on the wrapped object and not the wrapper because of how __setattr__ is defined. Would have had to use object.__setattr__() instead.
Anyway, I keep forgetting that __call__ is one of those methods that needs to be set on the class and not on the instance even in pure Python code. Not all dunder methods necessarily need to be unless things have changed from early Python 2 days. The rules around them can be non obvious.
Rather than create a full class definition nested inside of a normal function, which would prohibit easily creating derived custom ObjectProxy classes, a better approach may be a minimal ObjectProxy derived class shim inside of a __new__ method that inherits from the cls argument passed to __new__. This will though need to be tolerant of a derived class already overriding __call__ and also want to ensure same type name comes through, the latter meaning can't use normal nested class and so construct it manually.
class A:
def __init__(self, wrapped):
self.__wrapped__ = wrapped
def __new__(cls, wrapped):
print("orig", cls)
namespace = {}
if callable(wrapped) and "__call__" not in dir(cls):
def __call__(self, *args, **kwargs):
print("base")
return self.__wrapped__(*args, **kwargs)
namespace["__call__"] = __call__
NewClass = type(cls.__name__, (cls,), namespace)
print("new", NewClass)
return super().__new__(NewClass)
class B(A):
def __call__(self, *args, **kwargs):
print("derived")
return self.__wrapped__(*args, *kwargs)
def func():
print("func")
a = A(func)
print(type(a))
a()
b = B(func)
print(type(b))
b()
Next problem to consider then is that __wrapped__ can technically be assigned to and the wrapped object changed after the wrapper has been initialised. One would have to document a caveat that the behaviour of the class for the wrapper would adopt what was required only for the wrapped object initially supplied when the wrapper is created, and overriding __wrapped__ would not change it if requirement was different. Since expect is unlikely anyone would be reassigning __wrapped__ this would be acceptable.
@GrahamDumpleton I just found this issue from 2016 and it's still not fixed. If you are busy with other things these days, I can also update the python part of ObjectProxy and create a pull request. Would you want it or you already working on these?
I have already implemented a variant of dynamically adding a new class in __new__ as discussed to add __call__, __iter__, __next__, __aiter__ and __anext__. I also already added __aenter__, __aexit__ and __await__ direct to ObjectProxy.
I am still not keen on trying to change the class definition after the fact in rare case that __wrapped__ is assigned as there is more complexity to it than the code you suggested. Specifically, you should not delete any of the attributes if they were defined in a derived class, only if they were added dynamically. So have not made that change as yet and still thinking about it.
I haven't yet pushed changes up as I need to add more tests and have been busy with life stuff so haven't had time. I also still need to look more at dunder methods for matrix multiplication, which is another that currently isn't supported.
I modified my previous code snippet to check whether we are working with a dynamically added __call__ attribute or not before deleting it. This will not delete the __call__ attribute if it is defined by a derived class:
Great news you already implemented many dunder methods. But just like you gave the example of __matmul__, there are still many other unimplemented dunder methods. Example: __get__, __set__, __delete__
The issue is that self in the wrapper functions refers to the proxy object, not the original wrapped object. This can break descriptor behaviour because:
Identity issues: The descriptor receives the proxy as the instance parameter instead of the actual object it was designed to work with.
Type confusion: owner parameter might not match what the descriptor expects.
Binding context: Descriptors often rely on being bound to specific class hierarchies.
So I can't see that there is a generic proxy wrapper implementation one can have for special descriptor methods and binding protocol.
Binding for methods is complicated enough that wrapt has a special FunctionWrapper derived proxy type already to handle it all and that code is a mess of special cases.
I think you made a typo by writing proxy.attr instead of obj.attr, or even better, obj.proxy right?
Anyway, why would you pass self as the instance parameter? If you pass instance as the instance parameter and owner as the owner parameter there will be no problems. Like in this code:
That will teach me to bash out a response when running out the door and still groggy from a late night and lack of sleep. 🤣
So yes, I messed up badly and forgot the instance when doing binding comes from class the descriptor is used in. I thought I had something wrong, but was in a rush. Still not sure of a valid use case for having an object proxy wrapping a data descriptor. Non data descriptions, ie., binding behaviour as implemented by FunctionWrapper and as used in decorators, is more obvious.
Having an object proxy wrapping a data descriptor would be as easy as having an object proxy wrapping a non data descriptor. Just add __set__ and __delete__ dynamically in __new__ just like i showed how to for __get__. This way, you don't have to worry about what to do in __set__ and __delete__ in case __wrapped__ doesn't define them.
Those two don't print the same. They print 11 and 10 respectively. In order to solve this problem, i recommend changing in-place operators with something like this:
def__iadd__(self, other):
ifhasattr(self.__wrapped__, "__iadd__"):
self.__wrapped__+=otherreturnselfelse:
returntype(self)(self.__wrapped__+other) # This line probably contains bugs since current __new__ implementation inherits the class instead of copying and modifying its __dict__
This kind of behavior is also recommended in official python docs (falling back to __add__ when __iadd__ doesnt exists):
If __iadd__() does not exist, or if x.__iadd__(y) returns NotImplemented, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y
since a custom derived ObjectProxy type might be used which has a custom __init__() which accepts multiple arguments, or a single argument but where it isn't the final object to be wrapped, where in both cases arguments are interpreted in some other way to determine the final object to be wrapped, which is then passed to ObjectProxy base class __init__().
Have no idea what they are doing and why using ObjectProxy, but see example in:
The original problem in this case is a strange one where will need to think about. The problem lies with how if you have class attribute, when accessing via an instance of the class, it can result in the class attribute being copied to the instance. Because though when object proxy is used it isn't a literal, it copies the object reference and so it isn't a disconnected instance like when copies a literal. Thus always updating the single instance which at that point is shared between class and instance.
I am not sure that changing behaviour based on whether __iadd__ exists or not is sensible thing to do, as that ultimately isn't where the issue arises, but in the Python behaviour where it copies class attributes to instance attributes automatically.
import wrapt
class LiteralObjectProxy(wrapt.ObjectProxy):
pass
class A:
a = LiteralObjectProxy(10)
b = 10
def __setattr__(self, name, value):
if type(value) is LiteralObjectProxy:
value = LiteralObjectProxy(value.__wrapped__)
return object.__setattr__(self, name, value)
x = A()
x.a += 1
x.b += 1
print(x.a)
print(x.b)
del x.a
del x.b
print(x.a)
print(x.b)
because what Python is doing under the covers for += in this case is:
makes a copy of the attribute a from the class to a local variable
apply += to the local copy of the variable
assign the local copy of the variable to the instance (which triggers __setattr__)
If it had instead done:
copy the attribute a from the class to the instance (which triggers __setattr__)
apply += to the variable on the instance
then one could use the trick in __setattr__ above, provided had used the special object proxy type.
One would have to dig into how instruction interpreter in Python works in this special case of making copy of class attribute before applying in place operator. Relying on whether __iadd__ (or other in-place dunder methods) exist seems a bit fragile. There must be a more logical way that interpreter deals with this for itself. Whether one can do anything about it for a proxy wrapper have no idea.
In the really strange circumstance that someone wants to wrap a scalar which is class attribute and a constant, they could do:
import wrapt
class ConstantObjectProxy(wrapt.ObjectProxy):
def __get__(self, instance, owner):
return ConstantObjectProxy(self.__wrapped__)
class B:
a = ConstantObjectProxy(10)
b = 10
x = B()
x.a += 1
x.b += 1
print(x.a)
print(x.b)
del x.a
del x.b
print(x.a)
print(x.b)
I just can't think of any good uses cases for it, except perhaps to try and track how many times the constant is accessed.
I dont know what we can do about __init__ taking multiple arguments but I think changing behavior based on the existance of __iadd__ is the correct thing to do because if __add__ returns another object instead of modifying the current one, we shouldnt assign it to __wrapped__.
Also, this issue is not specific to builtin types. For example, same issue arises with Decimal from standard library:
Decimal is setup as an immutable type and doesn't define in-place operators. Thus for += it falls back to + being invoked and result assigned back to variable, where + is implemented such that it validates arguments are both Decimal and returns a new Decimal instance.
Of note here, if you had a derived Decimal class and were using += on it, it ignores that there was a derived class and always uses Decimal for the result (never derived class) which is then assigned back to the variable.
Not sure if object proxy could use a similar trick and ignore derived class and always return base object proxy always.
In other words can do much like what you suggest and have:
def __iadd__(self, other):
if hasattr(self.__wrapped__, "__iadd__"):
self.__wrapped__ += other
return self
else:
return ObjectProxy(self.__wrapped__ + other)
This would be done similarly for all mutating in-place operators.
Would just need to document that for this corner case if wrapping an immutable object and mutating in-place operator is used, that new object proxy is created which discards any derived class type and base ObjectProxy is always used.
If is a big deal that derived type is discarded, rather than use ObjectProxy explicitly, use a hook function that could be redefined in a derived class type, which accepts new wrapped object and derived method could then work out how to create instance of derived wrapper class using new wrapped object and any other attributes the current wrapper object has.
Version 2.0.0 has been released. It includes changes for in-place operators as discussed.
Of the other things discussed here, nothing has been done about __trunc__, __floor__, __ceil__, __buffer__ and __release_buffer__. I am still wary of adding something for those as they sit out side of the core object model and related to specific modules. Another which sits outside of core object model is __fspath__, which also not doing anything about at this time. Will consider them in the future if demonstrated use case arises which isn't solved by them being added in a custom object proxy.
I am going to close out this issue now. If there is a strong reason why it is believed the other dunder should be a part of default implementation, and not just a part of a users own custom derived ObjectProxy, create a new issue.
Activity
GrahamDumpleton commentedon Sep 23, 2025
It is not that simple.
Concerning
__iter__, it is arguable that it was a mistake to add it toObjectProxyin the first place as it has broken some code where people change behaviour based on a check ofhasattr(obj, "__iter__"). That is, this check would always returnTrueeven thoughiter()would fail and raise anAttributeError. So in hindsight it perhaps shouldn't have been added, even if thehasattrcheck is sort of an anti Python and people should just capture errors when doing iteration itself.As to
__call__is was never added because therecallable()always existed for checking if something was callable and was clear that adding__call__in base object proxy would cause issues straight away since people relied oncallable(). That people were relying onhasattr(obj, "__iter__")was not so obvious.Because of the issues with
__iter__, this is why the asynchronous versions were never added later when that feature was added to Python.As to
__next__, what is the specific use case since__iter__would call the__iter__of the wrapped object and so the returned object which provides__next__would not be a proxy object. Thus I don't see a direct reason why__next__should appear inObjectProxyas a default.If you are overriding
__iter__on a custom object proxy to wrap the result wheniter()is called, then you are already dealing with a mess of custom object proxies and so should be using such a custom object proxy to override__next__.As to the statement that "there are many dunder methods documented but are missing in ObjectProxy", they would fall into two cases. The first is that they didn't exist in older Python versions when wrapt was first written. The second is that it isn't appropriate for them to be added on an object proxy, or at least not as default behaviour. In other words, would be more appropriate to add them in a custom object proxy.
So can you provide some example use case of what you are trying to do where you need
__next__to be proxied.As to other dunder methods, list those you believe should be added by default on object proxy and provide specific examples so can understand why. In some cases where I learn of new dunder methods added in Python 3 they have been added, but only when asked and it makes sense to add them. I don't troll through each Python release looking for new dunder methods.
pyhacks commentedon Sep 23, 2025
In order to solve problems of
hasattr(obj, "__iter__")andcallable(obj)you can define a function generating a ObjectProxy and before instantiating it, modify it depending on the needs ofobj. Example for__call__:Usage example:

So for example, if
inspect.isawaitable(obj)is the reason you didn't implement__await__, you can solve it the same way.Proxying an iterator instead of a iterable:
E.g There are
__enter__and__exit__in ObjectProxy but their async versions are missing (__aenter__and__aexit__). And if you decide to implement__next__, there is also__anext__. This is not the complete list. There are some other missing methods too.GrahamDumpleton commentedon Sep 24, 2025
You can do that inside of the
__init__method itself, but that technique is only of use for the pure Python implementation ofObjectProxy.The pure Python implementation would rarely be used as it exists only as a fallback for when the C implementation isn't used for some reason.
In a C implementation of a Python object that sort of trick will not work because Python when it sees an object implemented in C, will only look in the
tp_slots of the C structure defining the type, and will ignore__iter__and__call__which are added as an attribute on the C object__dict__.To be able to use the trick that works for the pure Python object implementation it would be necessary to change
wraptso that the existing C implementation ofObjectProxyis renamed to_ObjectProxyand then create a smallObjectProxyPython implementation shim that inherits from C based_ObjectProxyand in the Python implementation of the derived class__init__then you could do it.I will need to research though what the implications of doing this will be though on other dunder attributes which have weird rules such as
__qualname__and__annotations__, plus the meta class hacks. These may have to be replicated in that derivedObjectProxyfor the C implementation as well as that in the C base class may no longer have the desired effect.Although I expect it may be minimal enough that not a concern, adding the extra Python class deriving from C implementation may have extra overhead as a result.
Anyway, your response didn't answer the main question I put to you, which was the example you had where having
__next__as a default onObjectProxywould be useful.pyhacks commentedon Sep 24, 2025
You can't do that inside
__init__because magic methods aren't automatically called when they are object attributes instead of class attributes. See this code:This gives:
TypeError: 'A' object is not callableYou also can't monkeypatch
ObjectProxyinside__init__because that change will be reflected on allObjectProxyinstances and it is possible that one instance should be callable and another shouldn't be. So that everyObjectProxyinstance should have its own type.I don't have a real world example but i tried to answer you by giving an example of proxying an iterator. Isn't being unable to correctly proxy an iterator bad enough?
Lastly, you also didn't answer a question of mine. Why didn't you implement
__aenter__and__aexit__?GrahamDumpleton commentedon Sep 24, 2025
Using:
would not have desired effect since that would set
__call__on the wrapped object and not the wrapper because of how__setattr__is defined. Would have had to useobject.__setattr__()instead.Anyway, I keep forgetting that
__call__is one of those methods that needs to be set on the class and not on the instance even in pure Python code. Not all dunder methods necessarily need to be unless things have changed from early Python 2 days. The rules around them can be non obvious.Rather than create a full class definition nested inside of a normal function, which would prohibit easily creating derived custom
ObjectProxyclasses, a better approach may be a minimalObjectProxyderived class shim inside of a__new__method that inherits from theclsargument passed to__new__. This will though need to be tolerant of a derived class already overriding__call__and also want to ensure same type name comes through, the latter meaning can't use normal nested class and so construct it manually.Next problem to consider then is that
__wrapped__can technically be assigned to and the wrapped object changed after the wrapper has been initialised. One would have to document a caveat that the behaviour of the class for the wrapper would adopt what was required only for the wrapped object initially supplied when the wrapper is created, and overriding__wrapped__would not change it if requirement was different. Since expect is unlikely anyone would be reassigning__wrapped__this would be acceptable.GrahamDumpleton commentedon Sep 25, 2025
Oh, and regard question "why didn't you implement
__aenter__and__aexit__", because they never existed whenwraptwas first written.pyhacks commentedon Sep 25, 2025
We can handle the case of assigning to
__wrapped__in__setattr__so that class structure will adapt to the new object:Actually I'm working on a code that requires overloading operators like
+=and in there this feature is pretty importantpyhacks commentedon Sep 28, 2025
@GrahamDumpleton I just found this issue from 2016 and it's still not fixed. If you are busy with other things these days, I can also update the python part of ObjectProxy and create a pull request. Would you want it or you already working on these?
GrahamDumpleton commentedon Sep 28, 2025
I have already implemented a variant of dynamically adding a new class in
__new__as discussed to add__call__,__iter__,__next__,__aiter__and__anext__. I also already added__aenter__,__aexit__and__await__direct toObjectProxy.I am still not keen on trying to change the class definition after the fact in rare case that
__wrapped__is assigned as there is more complexity to it than the code you suggested. Specifically, you should not delete any of the attributes if they were defined in a derived class, only if they were added dynamically. So have not made that change as yet and still thinking about it.I haven't yet pushed changes up as I need to add more tests and have been busy with life stuff so haven't had time. I also still need to look more at dunder methods for matrix multiplication, which is another that currently isn't supported.
pyhacks commentedon Sep 28, 2025
I modified my previous code snippet to check whether we are working with a dynamically added
__call__attribute or not before deleting it. This will not delete the__call__attribute if it is defined by a derived class:Is there any other problem with it now?
pyhacks commentedon Sep 28, 2025
Great news you already implemented many dunder methods. But just like you gave the example of
__matmul__, there are still many other unimplemented dunder methods. Example:__get__,__set__,__delete__GrahamDumpleton commentedon Sep 30, 2025
In respect of
__get__you would normally have:obj.attr→ Python callsattr.__get__(obj, type(obj))If you have basic proxying of
__get__then result is:proxy.attr→ Python callsproxy.__get__(obj, type(obj))→ callswrapped.__get__(obj, type(obj))The issue is that
selfin the wrapper functions refers to theproxyobject, not the original wrapped object. This can break descriptor behaviour because:instanceparameter instead of the actual object it was designed to work with.ownerparameter might not match what the descriptor expects.So I can't see that there is a generic proxy wrapper implementation one can have for special descriptor methods and binding protocol.
Binding for methods is complicated enough that
wrapthas a specialFunctionWrapperderived proxy type already to handle it all and that code is a mess of special cases.pyhacks commentedon Sep 30, 2025
In your sentence:
I think you made a typo by writing
proxy.attrinstead ofobj.attr, or even better,obj.proxyright?Anyway, why would you pass
selfas theinstanceparameter? If you passinstanceas theinstanceparameter andowneras theownerparameter there will be no problems. Like in this code:It prints the A object 3 times. No proxy object is printed.
GrahamDumpleton commentedon Sep 30, 2025
That will teach me to bash out a response when running out the door and still groggy from a late night and lack of sleep. 🤣
So yes, I messed up badly and forgot the instance when doing binding comes from class the descriptor is used in. I thought I had something wrong, but was in a rush. Still not sure of a valid use case for having an object proxy wrapping a data descriptor. Non data descriptions, ie., binding behaviour as implemented by FunctionWrapper and as used in decorators, is more obvious.
pyhacks commentedon Oct 1, 2025
Having an object proxy wrapping a data descriptor would be as easy as having an object proxy wrapping a non data descriptor. Just add
__set__and__delete__dynamically in__new__just like i showed how to for__get__. This way, you don't have to worry about what to do in__set__and__delete__in case__wrapped__doesn't define them.8 remaining items
pyhacks commentedon Oct 6, 2025
It just came to my mind: there is
decimalfrom standard library which provides a custom numeric classDecimal. If someone does:it will give error:
TypeError: type ObjectProxy doesn't define __trunc__ methodpyhacks commentedon Oct 6, 2025
I stumbled upon a strange behavior with in-place operators:
Those two don't print the same. They print 11 and 10 respectively. In order to solve this problem, i recommend changing in-place operators with something like this:
This kind of behavior is also recommended in official python docs (falling back to
__add__when__iadd__doesnt exists):GrahamDumpleton commentedon Oct 7, 2025
You can't technically do:
since a custom derived
ObjectProxytype might be used which has a custom__init__()which accepts multiple arguments, or a single argument but where it isn't the final object to be wrapped, where in both cases arguments are interpreted in some other way to determine the final object to be wrapped, which is then passed toObjectProxybase class__init__().Have no idea what they are doing and why using
ObjectProxy, but see example in:The original problem in this case is a strange one where will need to think about. The problem lies with how if you have class attribute, when accessing via an instance of the class, it can result in the class attribute being copied to the instance. Because though when object proxy is used it isn't a literal, it copies the object reference and so it isn't a disconnected instance like when copies a literal. Thus always updating the single instance which at that point is shared between class and instance.
I am not sure that changing behaviour based on whether
__iadd__exists or not is sensible thing to do, as that ultimately isn't where the issue arises, but in the Python behaviour where it copies class attributes to instance attributes automatically.GrahamDumpleton commentedon Oct 7, 2025
You can't even use a trick like:
because what Python is doing under the covers for
+=in this case is:afrom the class to a local variable+=to the local copy of the variable__setattr__)If it had instead done:
afrom the class to the instance (which triggers__setattr__)+=to the variable on the instancethen one could use the trick in
__setattr__above, provided had used the special object proxy type.One would have to dig into how instruction interpreter in Python works in this special case of making copy of class attribute before applying in place operator. Relying on whether
__iadd__(or other in-place dunder methods) exist seems a bit fragile. There must be a more logical way that interpreter deals with this for itself. Whether one can do anything about it for a proxy wrapper have no idea.GrahamDumpleton commentedon Oct 7, 2025
So this issue really relates only to builtin scalar types.
A
listin Python also has__iadd__, but in this situation it will end up shared between class and instance even without object proxy.GrahamDumpleton commentedon Oct 7, 2025
One question with this though is why anyone would deliberately wrap a scalar type (likely intended as a constant), which appears on the class.
GrahamDumpleton commentedon Oct 7, 2025
In the really strange circumstance that someone wants to wrap a scalar which is class attribute and a constant, they could do:
I just can't think of any good uses cases for it, except perhaps to try and track how many times the constant is accessed.
pyhacks commentedon Oct 7, 2025
I dont know what we can do about
__init__taking multiple arguments but I think changing behavior based on the existance of__iadd__is the correct thing to do because if__add__returns another object instead of modifying the current one, we shouldnt assign it to__wrapped__.Also, this issue is not specific to builtin types. For example, same issue arises with
Decimalfrom standard library:GrahamDumpleton commentedon Oct 8, 2025
Decimal is setup as an immutable type and doesn't define in-place operators. Thus for
+=it falls back to+being invoked and result assigned back to variable, where+is implemented such that it validates arguments are both Decimal and returns a new Decimal instance.Of note here, if you had a derived Decimal class and were using
+=on it, it ignores that there was a derived class and always uses Decimal for the result (never derived class) which is then assigned back to the variable.Not sure if object proxy could use a similar trick and ignore derived class and always return base object proxy always.
GrahamDumpleton commentedon Oct 8, 2025
In other words can do much like what you suggest and have:
This would be done similarly for all mutating in-place operators.
Would just need to document that for this corner case if wrapping an immutable object and mutating in-place operator is used, that new object proxy is created which discards any derived class type and base ObjectProxy is always used.
GrahamDumpleton commentedon Oct 8, 2025
If is a big deal that derived type is discarded, rather than use
ObjectProxyexplicitly, use a hook function that could be redefined in a derived class type, which accepts new wrapped object and derived method could then work out how to create instance of derived wrapper class using new wrapped object and any other attributes the current wrapper object has.GrahamDumpleton commentedon Oct 8, 2025
A similar thing is already done at:
Thus
ObjectProxyclass could thus define:Then in-place operators use:
Then custom derived
ObjectProxytype can specify__object_proxy__method to return instance of itself initialised in any special way.I think the chance of this being required is going to be non existent but at least have catered for it, and just need to document it.
GrahamDumpleton commentedon Oct 20, 2025
Version 2.0.0 has been released. It includes changes for in-place operators as discussed.
Of the other things discussed here, nothing has been done about
__trunc__,__floor__,__ceil__,__buffer__and__release_buffer__. I am still wary of adding something for those as they sit out side of the core object model and related to specific modules. Another which sits outside of core object model is__fspath__, which also not doing anything about at this time. Will consider them in the future if demonstrated use case arises which isn't solved by them being added in a custom object proxy.GrahamDumpleton commentedon Jan 15, 2026
I am going to close out this issue now. If there is a strong reason why it is believed the other dunder should be a part of default implementation, and not just a part of a users own custom derived ObjectProxy, create a new issue.