[Python-ideas] Decorators for variables

Matthias welp boekewurm at gmail.com
Fri Apr 1 10:18:14 EDT 2016

tldr: Using three method declarations or chaining method calls is ugly, why
not allow variables and attributes to be decorated too?

Currently the way to create variables with custom get/set/deleters is to
use the @property decorator or use property(get, set, del, doc?), and this
must be repeated per variable. If I were able to decorate multiple
properties with decorators like @not_none or something similar, it would
take away a lot of currently used confusing code.

Feedback is appreciated.


The current ways to define the getter, setter and deleter methods for a
variable or attribute are the following:

    def name():
        """ docstring """
       ... code

    def name():
        ... code

    def name():
        ... code


    var = property(getter, setter, deleter, docstring)

These two methods are doable when you only need to change access behaviour
changes on only one variable or property, but the more variables you want
to change access to, the longer and more bloated the code will get. Adding
multiple restrictions on a variable will for instance look like this:

    var = decorator_a(decorator_b(property(value)))


    def var(self):
        return decorator_a.getter(decorator_b..getter(self._value))
        ... etc

or even this

    def var(self):

I propose the following syntax, essentially equal to the syntax of function

    var = some_value

which would be the same as

    var = decorator(some_value)

and can be chained as well:

    var = some_value

which would be

   var = decorator(decorator_2(some_value))

or similarly

    var = decorator(decorator_2())
    var = some_value

The main idea behind the proposal is that you can use the decorator as a
standardized way to create variables that have the same behaviour, instead
of havng to do that using methods. I think that a lot can be gained by
specifying a decorator that can decorate variables or properties.

Note that many arguments will be the same as for function decorators (PEP
0318), but then applied to variable/property/attribute declaration.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160401/e39443a4/attachment.html>

More information about the Python-ideas mailing list