Is it possible to write a decorator that creates many properties at once?
Like instead of writing
class Test:
@property
def a(self):
return self.ref.a
@property
def b(self):
return self.ref.b
I’d like to write
class Test:
@properties("a", "b")
def prop(self, name):
return getattr(self.ref, name)
Is it possible? Do you recommend it?
Recall that a decorator
is just syntactic sugar for writing
So it is not possible for a method decorator to result in more than one method (or property, etc.) to be added to a class.
An alternative might be a class decorator that injects the properties:
However it’d usually be clearer to have each property present within the body of the class:
where
forward_propertyreturns a property object as appropriate implementing the descriptor protocol. This is friendlier to documentation and other static analysis tools, as well as (usually) the reader.