【问题标题】:Adding parameter to decorator removes cls parameter向装饰器添加参数会删除 cls 参数
【发布时间】:2020-02-06 14:26:47
【问题描述】:

我想在我的烧瓶应用程序中记录 MongoEngine 文档,如 here 所述。但我也希望能够排除此文档类具有的某些属性。

如果我给装饰器的应用函数一个附加参数excludes,则不再给出 cls 参数。

Traceback (most recent call last):
  File ".../test.py", line 26, in <module>
    @__log_update.apply(excludes=[])
TypeError: apply() missing 1 required positional argument: 'cls'

在简化代码中

def handler(*events):
    """
    Signal decorator to allow use of callback functions as class decorators.
    """
    def decorator(fn):
        def apply(cls, excludes=[]):
            for exclude in excludes:
                print(exclude)

            for event in events:
                event.connect(fn, sender=cls)
            return cls

        fn.apply = apply
        return fn

    return decorator

@handler()
def __log_update(*args, **kwargs):
    pass


@__log_update.apply(excludes=['testString'])
class Test(object):
    testString = ''
    testInt = 0

但是当只使用@__log_update.apply 没有任何参数时,cls 参数被给出并且应该是&lt;class '__main__.Test'&gt;

我需要两者都做日志记录。

【问题讨论】:

    标签: python logging decorator


    【解决方案1】:

    关于 decorator 的工作原理。

    当你这样应用它时(无论有无参数):

    @__log_update.apply()
    

    调用的结果应该是一个装饰器本身,然后应用到底层
    您需要一个额外的层来使.apply() 函数返回一个类装饰器:

    def handler(*events):
        """
        Signal decorator to allow use of callback functions as class decorators.
        """
        def decorator(fn):
            def apply(excludes=[]):
                def class_decor(cls):
                    for exclude in excludes:
                        print(exclude)
    
                    for event in events:
                        event.connect(fn, sender=cls)
                    return cls
                return class_decor
    
            fn.apply = apply
            return fn
    
        return decorator
    
    @handler()
    def __log_update(*args, **kwargs):
        pass
    
    
    @__log_update.apply(excludes=['testString'])
    class Test(object):
        testString = ''
        testInt = 0
    

    【讨论】:

      猜你喜欢
      • 2010-12-23
      • 2021-09-17
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 2013-09-14
      • 2021-07-28
      • 2021-03-28
      • 2023-04-03
      相关资源
      最近更新 更多