[Python-ideas] Method signature syntactic sugar (especially for dunder methods)

Nathan Dunn nathanfdunn at gmail.com
Sun Nov 6 01:28:34 EST 2016


Python has very intuitive and clear syntax, except when it comes to method
definitions, particularly dunder methods.


class Vec(object):
   def __init__(self, x, y):
       self.x, self.y = x, y

   def __add__(self, other):
       return Vec(self.x + other.x, self.y + other.y)

   def __getitem__(self, key):
       return self.x if key == 'x' else self.y if key == 'y' else None

   def __contains__(self, item):
       return self.x == item or self.y == item

   def __bool__(self):
       return self.x or self.y

   def display(self):
       print('x:', self.x, 'y:', self.y)


Having to declare a self parameter is confusing since you don't pass
anything in when you call the method on an instance (I am aware of bound
vs. unbound methods, etc. but a beginner would not be). The double
underscores are also confusing.

I propose syntactic sugar to make these method signatures more intuitive
and clean.


class Vec(object):
   def class(x, y):
       self.x, self.y = x, y

   def self + other:
       return Vec(self.x + other.x, self.y + other.y)

   def self[key]:
       return self.x if key == 'x' else self.y if key == 'y' else None

   def item in self:
       return self.x == item or self.y == item

   def bool(self):
       return self.x or self.y

   def self.display():
       print('x:', self.x, 'y:', self.y)


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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161106/324c59bf/attachment.html>


More information about the Python-ideas mailing list