(Not sure why this is on python-ideas - wouldn't python-list be more appropriate? Keeping it where it is for now though.) On Thu, Jul 2, 2020 at 5:14 PM Greg Ewing <greg.ewing@canterbury.ac.nz> wrote:
The @property.getter and @property.setter decorators are clever, but they have the disadvantage that you end up writing the name of the property no less than 5 times, all of which have to match.
Thinking there must be a better way, I came up with this:
def Property(name, bases, dict): return property(dict.get('get'), dict.get('set'))
which allows you to write
class Test:
class foo(metaclass = Property):
def get(self): print("Getting foo") return self._foo
def set(self, x): print("Setting foo to", x) self._foo = x
test = Test() test.foo = 42 print(test.foo)
Output: Setting foo to 42 Getting foo 42
I quite like the use of class blocks as namespaces, but I'm not a fan of metaclassing. A decorated class is way cleaner in the source code. How about this? def Property(ns): return property(*[getattr(ns, k, None) for k in ("fget", "fset", "fdel", "__doc__")]) class Test: @Property class foo: """Docstring for foo""" def fget(self): print("Getting foo") return self._foo def fset(self, x): print("Setting foo to", x) self._foo = x Same output as yours, and it's easy to support fdel, and a docstring. ChrisA