Decorating a decorator

夙愿已清 提交于 2021-02-10 05:40:55

问题


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:

  1. Is it possible to modify a decorator's argument?
  2. If true, then how can I achieve it?

来源:https://stackoverflow.com/questions/63371665/decorating-a-decorator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!