[Python-ideas] The Descriptor Protocol...

Nick Coghlan ncoghlan at gmail.com
Thu Mar 3 12:36:02 CET 2011

On Thu, Mar 3, 2011 at 2:10 AM, Raymond Hettinger
<raymond.hettinger at gmail.com> wrote:
> b) make the developer duplicate the attribute name when constructing the
> descriptor:-
> class Person(object):
>    name    = Str('name')
>    address = Str('address')
> which, well, just smells, and conflicts with step 3 of TDD ;^)
> Yes, option b is the usual way to do it (there are a number of recipes that
> use this approach).
> For the most part, that shouldn't be an unfamiliar pattern to Python
> developers.  For example, named tuples repeat the name:
>    Point = namedtuple('Point', ('x', 'y')).
> Sometimes the language provides syntax to do the work for us, like "class A:
> ..." instead of "A = type('A', (), {})", but for other situations, it isn't
> unusual to pass in a name as a string literal so that an object will know
> its own name.
> For Python 4, perhaps you can convince Guido to add a key argument to the
> signature for __get__ and __set__.  It would make a handful of recipes a bit
> prettier at the expense of being a total waste for all the other use cases
> that don't need it.
> I think everyone who writes a descriptor that needs the "key" will chafe at
> the current design.  It bugged me at first, but the workaround is easy and
> after a while it doesn't seem as bothersome.

Rather than a descriptor specific answer, something that covered the
namedtuple use case as well would be nice. That is, something that
made it feasible to reference the name on the left hand side of a
simple assignment without needing to repeat it as a string with the
same contents.

# Straw-man idea

class Person:
  as name = Str(as)
  as address = Str(as)

as Point = namedtuple(as, 'x y')

Basically just a variant on the ordinary assignment statement that
makes the target name available for reference in the source
expression. I'm dubious about the merits of that particular
suggestion, but I think it is a much better problem to try to tackle
than changing the descriptor protocol.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list