Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #100005

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

From Ian Kelly <ian.g.kelly@gmail.com>
Newsgroups comp.lang.python
Subject Re: [Python-ideas] Missing Core Feature: + - * / | & do not call __getattr__
Date 2015-12-04 09:41 -0600
Message-ID <mailman.199.1449243747.14615.python-list@python.org> (permalink)
References <CAOs8ta06yhq+C+w805k53fpMwqzDD0MuWnLt7b=vxazvr_N1fQ@mail.gmail.com>

Show all headers | View raw


On Fri, Dec 4, 2015 at 7:20 AM, Stephan Sahm <Stephan.Sahm@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?

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: [Python-ideas] Missing Core Feature: + - * / | & do not call __getattr__ Ian Kelly <ian.g.kelly@gmail.com> - 2015-12-04 09:41 -0600

csiph-web