[Python-ideas] Assignment decorators (Re: The Descriptor Protocol...)

Raymond Hettinger raymond.hettinger at gmail.com
Fri Mar 4 03:25:05 CET 2011

On Mar 3, 2011, at 5:40 PM, Greg Ewing wrote:

> Guido van Rossum wrote:
>> Greg, what is your use case for passing the lhs name into the
>> function?
> I've found two so far:
> * Named tuples
> * OverridableProperty instances in PyGUI

I wouldn't like to see named tuples used as justification for the proposed syntax change.   

In a typical use of a named tuple, the name gets referred to many times and the name gets included in docs and docstrings:

Point = namedtuple('Point', 'x, y, z, color)
 . . .

p = Point(ax, ay, az, acolor)
q = Point(qx, qy, qz, qcolor)
def midpoint(u, v, mixer):
      'Create a new Point half-way between u and v.  Mix the colors with the given function'
      return Point(avg(u.x, v.x), avg(u.y, v.y), avg(u.z, v.z), mixer(u.color, v.color))

So, the syntax change would save only one out of very many uses.   It's not much different than class definitions which get defined once, become part of the API, and are accessed in many places.  Optimizing a few characters in the definition line is not win.  If you need to change the name later, it will need to get changed in many places (global substitution).

Named tuples do most of their work after the definition is made (instantiating new instances or accessing their parts using attribute lookup). In a typical module using named tuples, fewer than a dozen characters would be saved out of the entire file.  I don't see that as much of a win.

The last concern is that the proposal may change the way a person thinks about named tuples.  It suggests that the only way to use them is to assign them.  But there are other ways:

       class Point(namedtuple('Point', 'x y')):
            def __repr__(self):
                  print('<{:6.3f} | {:6.3f}>'.format(self))

There may be other compelling use cases for assignment decorators but I don't think named tuples are among them.


More information about the Python-ideas mailing list