检查函数参数的装饰器

2024-10-02 22:37:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要为一个函数创建decorator,这样,如果一个特定函数在一行中使用相同的参数调用了两次,它将不会运行,而是返回None

被修饰的函数可以有任意数量的参数,但不能有关键字参数

例如:

@dont_run_twice
def myPrint(*args):
    print(*args)

myPrint("Hello")
myPrint("Hello")  #won't do anything (only return None)
myPrint("Hello")  #still does nothing.
myPrint("Goodbye")  #will work
myPrint("Hello")  #will work

Tags: 函数runnonehello参数数量defargs
2条回答
def filter_same_args(func):
    args_store = set()

    def decorator(*args):
        if args in args_store:
            return None

        args_store.add(args)
        func(*args)
    
    return decorator

@filter_same_args
def my_print(*args):
    print(*args)


my_print('one', 'two', 3)
my_print('one', 'two', 3)
my_print('one', 'two', 3, 4)

看看这个简单的方法是否适合你

prev_arg = ()

def dont_run_twice(myPrint):

    def wrapper(*args):
        global prev_arg

        if (args) == prev_arg:
            return None

        else:
            prev_arg = (args)

        return myPrint(*args)

    return wrapper


@dont_run_twice
def myPrint(*args):
    print(*args)

相关问题 更多 >