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

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Mar 4 02:40:41 CET 2011

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

> Also it seems that one couldn't decorate all but the simplest assignments:
> @dec
> lhs.attr = rhs
> # lhs.attr = dec('lhs.attr', rhs)  ???

That would be disallowed -- the target would be restricted to
a bare name. This is no worse than the corresponding restriction
for 'def' and 'class'.

> The use case I can think of for the first example would be to declare
> fields in a model class that know their own field name

> ... the @decorator syntax has the
> disadvantage of requiring at least two lines per field, whereas the
> current solution requires only one line

Yes, that's a valid criticism. The 'def' version would address it.

 > But that use case is
 > covered pretty well by metaclasses,

I'm not convinced that metaclasses are a general solution to this
kind of problem.

I had an interesting experience recently with SqlAlchemy, where there
is a Table class having a metaclass that does magical things with the
contents of the class dict when the class is created. It turns out
you can't subclass the Table class using the normal Python techniques,
because the metaclass magic gets triggered too soon. To work around
this they provide a flag you can use to suppress the magic, but it's
an ugly kludge.

There's also the problem that you can only use *one* metaclass at
a time, so if you want a class that makes use of features provided
by two different metaclasses, you're out of luck. For example, if
I were relying on a metaclass to set up my OverridableProperty
descriptors, and I wanted a Django model class to have some of
those properties, I wouldn't be able to do it, because the
metaclasses would conflict.


More information about the Python-ideas mailing list