【问题标题】:Wrapper for Python DecoratorsPython 装饰器的包装器
【发布时间】:2021-07-25 03:37:08
【问题描述】:

最近,我开始更广泛地使用装饰器。对于一个项目,我需要不同的装饰器,如下图所示:

def param_check(fn=None, arg1=None, arg2=None):
    def deco(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):

            #this is the only part that really changes
            result = func(arg1, arg2)


            return fn(result, *args, **kwargs)
        return wrapper
    if callable(fn): return deco(fn)
    return deco

def func(arg1, arg2):
   ...do something...
   .
   .
   ...return something

但是,由于这是大量重复的代码,我想知道构建一个只接受一个函数然后返回一个新装饰器的包装函数的最 Pythonic 方式是什么?我尝试了几种方法,但都没有成功。我想知道是否有人知道如何做到这一点。

【问题讨论】:

    标签: python python-decorators


    【解决方案1】:

    我认为您只想添加另一层:最外层将接受一个参数,这就是在 wrapper 内部调用的内容,而不是对 func 的硬编码引用。

    def decorator_maker(decfun):
        def parameterized_decorator(fn=None, arg1=None, arg2=None):
            def deco(fn):
                @wraps(fn)
                def wrapper(*args, **kwargs):
    
                    #this is the only part that really changes
                    result = decfun(arg1, arg2)
    
    
                    return fn(result, *args, **kwargs)
                return wrapper
            if callable(fn): return deco(fn)
            return deco
        return parameterized_decorator
    
    
    def func(arg1, arg2):
        pass
    
    param_check = decorator_maker(func)
    
    # Or...
    # @decorator_maker
    # def func(arg1, arg2):
    #    ...
    
    @param_check(3, 4)
    def f(result):
        ...
    

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-04
      • 2018-03-07
      • 2018-10-03
      • 2020-06-15
      • 1970-01-01
      相关资源
      最近更新 更多