@property simultaneous setter and getter

Devin Jeanpierre jeanpierreda at gmail.com
Sat Dec 21 13:07:35 CET 2013

On Sat, Dec 21, 2013 at 2:14 AM, Peter Otten <__peter__ at web.de> wrote:
> If I were to implement something like this I'd probably use the old trick
> with nested functions:
> def getset(f):
>     funcs = f()
>     return property(funcs.get("get"), funcs.get("set"))
> class A(object):
>     @getset
>     def attr():
>         def get(self):
>             print("accessing attr")
>             return self._attr
>         def set(self, value):
>             print("setting attr to {}".format(value))
>             self._attr = value
>         return locals()
> if __name__ == "__main__":
>     a = A()
>     a.attr = 42
>     print(a.attr)
> This has been around awhile, but I don't see widespread adoption...

IMO: Because classes are the normal way of grouping functions together
in Python.

In fact, we already have an interface for these classes: the
descriptor protocol. Unfortunately it's pretty annoying to define
"properties" directly using the descriptor protocol, because its
__get__ is weird and difficult to remember how to make work correctly.
Also because the decorator making this convenient has been vanished in
python 3. ;)

class A(object):
    _attr = None

    class attr(object):
        def __get__(self, instance, owner):
            if instance is None:
                return self

            print "accessing attr"
            return instance._attr

        def __set__(self, instance, value):
            print "setting attr to {}".format(value)
            instance._attr = value

a = A()
a.attr = 42

A().attr = 3

-- Devin

More information about the Python-list mailing list