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

Stephan Sahm Stephan.Sahm at gmx.de
Fri Dec 4 08:55:52 EST 2015


Thanks for the constructive response!

this is good to know, however it still forces me make such a dynamic
placeholder explicit for every single operator.
Still, I could put everything in a Mixin class so that it is in fact useful
to clean up code.

However, in the long run, such placeholders seem like an unnecessary
overhead to me.



I myself thought whether one can insert the methods into the class itself
using __new__ or something else concerning meta-classes. My background is
however not good enough in order to seriously explore this direction.

Any further suggestions?


On 4 December 2015 at 14:50, Amaury Forgeot d'Arc <amauryfa at gmail.com>
wrote:

> 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/18100f96/attachment-0001.html>


More information about the Python-ideas mailing list