On Fri, Dec 4, 2015 at 7:20 AM, Stephan Sahm <stephan.s...@gmx.de> wrote: > 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. > > 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.
The cited reason is "speed optimizations": https://docs.python.org/3/reference/datamodel.html#special-method-lookup But there may be other reasons as well. __getattr__ and __getattribute__ are meant to implement *attribute* lookup. Special methods are best not regarded as attributes (although they can be looked up as such), but as implementation of class behavior. You'll note that special methods also aren't resolved in the instance dict, but only in the class dict; this is viewed as a matter of correctness, so that special methods work correctly on class objects (invoking the metaclass) as well as on instances. In some cases there may also be a chicken-and-egg problem; should Python call __getattribute__ in order to resolve the __getattribute__ method? -- https://mail.python.org/mailman/listinfo/python-list