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

Larry Hastings larry at hastings.org
Wed Mar 16 05:49:38 CET 2011



In case you'd like to play with assignment decorators using what's 
possible with current syntax, I present the "assign" decorator:

    def assign(fn):
       return fn(fn.__name__)

    class C(object):
       @assign
       def x(name):
         return "<<" + name + ">>"

    c = C()
    print(c.x)

This prints "<<x>>" in Python 3.  A function was called at the 
definition time of "x"; it knew the name of the variable, and it was 
able to compute the value of the class attribute, and you only had to 
specify the variable name once.

I'm not suggesting this be used for production code--it's awful magic.  
But this could be used to prototype use cases for assignment decorators.


/larry/



More information about the Python-ideas mailing list