python - 从字符串添加装饰器

标签 python python-3.x python-decorators

我有一个这样的装饰器:

def foo(func):
    """Will print the args and kwargs of a func"""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print('Do I have args?')
        print(args, kwargs, sep='\n')

        return func(*args, **kwargs)

    return wrapper

还有像这样的“装饰者制造者”:

def add_checks(*decorators):
    """Adds decorators to a func"""
    def check(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # how do I add here the `*decorators`?
            return func(*args, **kwargs)

        return wrapper

    return check

如何通过字符串添加装饰器?所以它是这样的:

@add_checks('foo')
def bar(a, b, c=1):
    return (a * b) / c

print(bar(5, 2, c=5))
>>> Do I have args?
>>> [5, 2]
>>> {'c': 5}
>>> 2

最佳答案

您只需要迭代*decorators:

import functools


def foo(func):
    """Will print the args and kwargs of a func"""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print('Do I have args?')
        print(args, kwargs, sep='\n')
        #return func(*args, **kwargs)

    return wrapper


def add_checks(*decorators):
    """Adds decorators to a func"""
    def check(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for dec in decorators:
                if isinstance(dec, str):
                    # lookup for the function in globals()
                    globals()[dec](func)(*args, **kwargs)
                else:
                    dec(func)(*args, **kwargs)

            return func(*args, **kwargs)

        return wrapper

    return check


@add_checks(foo)  # reference to the function!
def bar(a, b, c=1):
    return (a * b) / c


@add_checks("foo")
def bar_strDecorated(a, b, c=1):
    return (a * b) / c


print(bar(5, 2, c=5))
print(bar_strDecorated(5, 2, c=5))

输出:

Do I have args?
(5, 2)
{'c': 5}
2.0
Do I have args?
(5, 2)
{'c': 5}
2.0

关于python - 从字符串添加装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65200537/

相关文章:

python - 如何使用基本操作更改列表中的值?

python - getter 和 setter 的属性装饰器

python - 在 Python 中添加将字符串转换为小写的装饰器

python - 如果子字符串位于单词末尾,则手动字符串 'in' 函数不起作用

python - 函数返回值的长度

python - 如何在不复制的情况下更改列表列表?

python - 如何通过 sys.argv 执行函数

python - imshow 彩色图像,错误显示为蓝色

python - sklearn 中带有partial_fit 的 GridSearchCV/RandomizedSearchCV

python - 在 Python 中,如何定义一个函数包装器来验证具有特定名称的参数?