Fallback for operator and other dunder methods
Dom Grigonis
dom.grigonis at gmail.com
Tue Jul 25 22:22:18 EDT 2023
To illustrate what I was trying to achieve:
class A:
def __init__(self, arr):
self.arr = arr
def __getattr__(self, name):
arr_method = getattr(self.arr, name)
def wrapper(*args, **kwargs):
new_arr = arr_method(*args, **kwargs)
return type(self)(new_arr)
return wrapper
a = A(np.ones((1, 1)))
print(a.sum().arr) # 1
print(a + 1) # TypeError: unsupported operand type(s) for +: 'A' and 'int'
Is there a way to achieve it without actually implementing operators?
I have looked at Proxy objects, but they do not seem suited to achieve this. (e.g. wrapt)
If there is no way to do this, wouldn’t it be sensible to have a new method, say ‘__getattrspecial__’? Either with ability to customise for which operators it is being called or not.
—Nothing ever dies, just enters the state of deferred evaluation—
Dg
More information about the Python-list
mailing list