[Python-3000] Assignment decorators, anyone?

Steven Bethard steven.bethard at gmail.com
Mon Jun 12 20:03:21 CEST 2006

On 6/8/06, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> I think I've come across a use case for @decorators
> on assignment statements.
> I have a function which is used like this:
>    my_property = overridable_property('my_property', "This is my property.")
> However, it sucks a bit to have to write the name of
> the property twice. I just got bitten by changing the
> name of one of my properties and forgetting to change
> it in both places.
> If decorators could be applied to assignment statements,
> I'd be able to write it as something like
> @overridable_property
> my_property = "This is my property."
> (This would require the semantics of assignment
> decoration to be defined so that the assigned name
> is passed to the decorator function as well as the
> value being assigned.)
> On the other hand, maybe this is a use case for
> the "make" statement that was proposed earlier.

Yes, `PEP 359`_ provided functionality like this, but since it's
withdrawn, another option for you is something like::

    class my_property:
        __metaclass__ = overridable_property
        text = "This is my property."

where overridable_property looks something like:

    def overridable_property(name, args, kwargs):
        text = kwargs.pop('text')
        # do whatever you normally do with name and text

(This is basically all the "make" statement was doing under the covers
anyway.)  Of course, the end result is that you use a class statement
to create something that isn't a class, but at least you manage to
avoid writing "my_property" twice.

.. _PEP 359: http://www.python.org/dev/peps/pep-0359/

Grammar am for people who can't think for myself.
        --- Bucky Katt, Get Fuzzy

More information about the Python-3000 mailing list