As many of you probably know, you can use decorators (sometimes called annotations, in eg Java) to do automagic registration of objects into easily usable data structures, like lists or dictionaries, in such a way that you don’t have to update these “meta” data strucutres; any new code you decorate gets into it automatically.
This has a variety of uses in, eg, event-based programming, the factory pattern, etc.
When implementing your own decorators, especially if you need args/kwargs, you’ve probably seen this answer from StackOverFlow, whose code I will reproduce here:
def decorator_factory(argument):
def decorator(function):
def wrapper(*args, **kwargs):
funny_stuff()
something_with_argument(argument)
result = function(*args, **kwargs)
more_funny_stuff()
return result
return wrapper
return decorator
My question is two-fold:
- When implementing a decorator, is there any reason to go beyond the 2-level
decorator -> wrapper
nesting implementation? - Are there cases where you might have more than 2 of decorators on, eg, a classmethod or property? I’ve only ever seen the likes of
@staticmethodnt@my_factory.register
ijustlovemath is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.