@property simultaneous setter and getter

Peter Otten __peter__ at web.de
Sat Dec 21 05:14:37 EST 2013


Brian Bruggeman wrote:

> Is this something that would be pep-able?
> 
> https://gist.github.com/brianbruggeman/8061774

There's no need to put such a small piece of code into an external 
repository.

> class someAwesomeClass(object):
>     """ an example """
>     
>     @property
>     def some_attr(self, value=None):
>         """
>         Implementation of a setter and getter property in one
>         """
>         attr = "__local_attr__"
>         if not hasattr(self, attr):
>             setattr(self, attr, value)
>         if (value != None and hasattr(self, attr)):
>             setattr(self, attr, value)
>         return getattr(self, attr)

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...




More information about the Python-list mailing list