python - 向装饰器添加参数会删除 cls 参数

标签 python logging decorator

我想按照描述在我的 Flask 应用程序中记录 MongoEngine 文档 here 。但我也希望能够排除该文档类具有的某些属性。

如果我给装饰器的apply函数一个额外的参数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 参数,且为 <class '__main__.Test'>正如它应该的那样。

我需要两者来进行日志记录。

最佳答案

关于装饰器的工作原理。

当你像这样应用它时(无论带或不带参数):

@__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

关于python - 向装饰器添加参数会删除 cls 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58300941/

相关文章:

sorting - 重新排序由字典组成的列表的 Pythonic 方式是什么?

python - 从信号频谱图中提取峰

java - 是否可以使用 Logback 为每个日志事件添加序列号?

Python Sphinx autodoc 和装饰成员

python - 在 Python 的属性上使用装饰器处理异常

python - Docker 构建生成许多未命名的镜像

Python 导入错误 : No module named webpack_loader

bash - 具有文件描述符的重复 IO

java - Log4J 每 x 秒记录一次消息?

python - 在 python 的 __init__ 处获取装饰器内的方法类名