[Python-ideas] Method signature syntactic sugar (especially for dunder methods)
Nick Coghlan
ncoghlan at gmail.com
Sun Nov 6 02:22:19 EST 2016
On 6 November 2016 at 16:28, Nathan Dunn <nathanfdunn at gmail.com> wrote:
> There are some immediate problems with this, such as `bool(self)` being
> indistinguishable from a regular method signature and `class(x, y)` not
> declaring the `self` identifier. These and other problems can be solved to
> some extent, but I thought I would see if there is any interest around this
> before going too in depth.
The syntax is the least confusing part of special method overrides, so
if folks are still struggling with that aspect of defining them, there
are plenty of other things that are going to trip them up.
>From your examples:
* __add__ is only part of the addition protocol, there is also
__radd__ and __iadd__
* likewise, there is not a one-to-one correspondence between the
bool() builtin and the __bool__() special method (there are other ways
to support bool(), like defining __len__() on a container)
* the mapping protocol covers more than just __getitem__ (and you also
need to decide if you're implementing a mapping, sequence, or
multi-dimensional array)
If the current syntax makes people think "This looks tricky and
complicated and harder than defining normal methods", that's a good
thing, as magic methods *are* a step up in complexity from normal
method definitions, since you need to learn more about how and when
they get called and the arguments they receive, while normal methods
are accessed via plain function calls.
My concern with the last suggestion is different (permitting the first
parameter to be specified on the left of the method name), which is
that it would break the current symmetry between between name binding
in def statements and target binding in assignment statements -
currently, all permitted binding targets in def and class statements
behave the same way as they do in normal assigment statements, and
throw SyntaxError otherwise. With the proposed change, we'd face the
problem that the following would both be legal, but meant very
different things:
cls.mymethod = lambda self: print(self)
def cls.mymethod(self): print(self)
The former is already legal and assigns the given lambda function as a
method on the existing class, `cls`
The latter currently throws SyntaxError.
With the proposed change, rather than throwing SyntaxError as it does
now, the latter would instead be equivalent to:
def mymethod(cls, self): print(self)
which would be a very surprising difference in behaviour.
Regards,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list