【问题标题】:decorator that check the args of a function检查函数参数的装饰器
【发布时间】:2021-04-14 11:22:03
【问题描述】:

我需要为一个函数创建装饰器,这样如果一个特定的函数连续两次以相同的参数被调用,它就不会运行,而是返回 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

【问题讨论】:

标签: python python-decorators


【解决方案1】:

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

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)

【讨论】:

  • 编辑:修复了一个小错误。现在工作正常。
【解决方案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)

【讨论】:

    猜你喜欢
    • 2013-02-24
    • 2019-07-29
    • 2014-07-21
    • 2011-07-26
    • 2011-06-25
    • 1970-01-01
    • 2014-11-03
    • 2014-10-15
    • 2015-06-25
    相关资源
    最近更新 更多