[Python-ideas] Missing Core Feature: + - * / | & do not call __getattr__

Amaury Forgeot d'Arc amauryfa at gmail.com
Fri Dec 4 08:50:05 EST 2015


Le ven. 4 déc. 2015 à 14:21, Stephan Sahm <Stephan.Sahm at gmx.de> a écrit :

> Dear all,
>
> I just stumbled upon a very weird behaviour of python 2 and python 3. At
> least I was not able to find a solution.
>
> *The point is to dynamically define __add__, __or__ and so on via
> __getattr__* (for example by deriving them from __iadd__ or similar in a
> generic way).
> However this very intuitive idea is currently NOT POSSIBLE because * - * /
> & | and so on just bypass this standard procedure.
>

It is possible if you use indirection, and another name for the dynamic
methods:

class C:
    def __add__(self, other):
        try:
            method = self.dynamic_add
        except AttributeError:
            return NotImplemented
        else:
            return method(other)

obj = C()
print(obj + 1)  # raises TypeError
obj.dynamic_add = lambda other: 42 + other
print(obj + 1)  # 43


>
> I found two stackoverflow contributions stating this:
>
> http://stackoverflow.com/questions/11629287/python-how-to-forward-an-instances-method-call-to-its-attribute
>
> http://stackoverflow.com/questions/33393474/lazy-evaluation-forward-operations-to-deferred-value
>
> Neither the mentioned posts, nor I myself can see any reason why this is
> the way it is, nor how the operators are actually implemented to maybe
> bypass this unintuitive behaviour.
>
> Any help? Comments? Ides?
>
> best,
> Stephan
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151204/b8f8a686/attachment.html>


More information about the Python-ideas mailing list