问题
I tried to do some argument modification on a decorator which decorates a function.
The original code looks like
@original_decorator(arg=some_object)
def calculate(a, b):
# complex business logic
raise Exception()
where original_decorator
is responsible for exception handling.
What I want to achieve is to do some temporary modification on some_object
and restore it's property after function returned.
And I've tried the following
def replace_arg(arg, add_some_property):
def decorator_wrapper(decorator_func):
def decorator_inner(*decorator_args, **decorator_kwargs):
def actual_wrapper(actual_func):
def actual_inner(*actual_args, **actual_kwargs):
original = arg['func']
arg['func'] = add_some_property
decorator_kwargs['arg'] = arg
result = actual_func(*actual_args, **actual_kwargs)
arg['func'] = original
return result
return actual_inner
return actual_wrapper
return retry_inner
return retry_wrapper
Also tried to place the modification logic in decorator_inner
, but neither worked.
My Questions:
- Is it possible to modify a decorator's argument?
- If true, then how can I achieve it?
来源:https://stackoverflow.com/questions/63371665/decorating-a-decorator