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

Guido van Rossum guido at python.org
Fri Mar 4 07:03:05 CET 2011

On Thu, Mar 3, 2011 at 9:11 PM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> def overridable_property(name, doc = None):
>    """Creates a property which calls methods get_xxx and set_xxx of
>    the underlying object to get and set the property value, so that
>    the property's behaviour may be easily overridden by subclasses."""
>    getter_name = intern('get_' + name)
>    setter_name = intern('set_' + name)
>    return property(
>        lambda self: getattr(self, getter_name)(),
>        lambda self, value: getattr(self, setter_name)(value),
>        None,
>        doc)
> It needs to know the name of the property so that it can build
> the correct method names. That's an implementation detail that
> the user shouldn't have to care about, but I'm forced to expose
> it because of a deficiency in the language. It's like a house
> with pieces of plumbing sticking out of the walls instead of
> being hidden away. It works, but it's ugly and annoys you every
> time you look at it.

I agree it's not a good use case for a metaclass. I still don't think
it's worth adding decorated assignment for; the annoyance is pretty
minor and there are surely many other language warts that one might
like to smooth over (but not with decorators).

I don't even think it's a great use case for a decorated assignment; I
don't think that

  foo = "Whatever"

looks particularly elegant. Especially if you had a bunch of these in
a row, I think I'd prefer the one-liner-with-string-literal over the
two-liner-with-decorator. Though I don't know if these frequently
occur in bunches. (The field/property definitions in Django and App
Engine definitely do.)

--Guido van Rossum (python.org/~guido)

More information about the Python-ideas mailing list