Larisa Balter Katz
Larisa Balter Katz

Reputation: 31

decorator that check the args of a function

I need to create decorator for a function so that if a particular function is called twice in a row with the same parameters, it will not run, and return None instead.

The function being decorated can have any number of parameters, but no keyword arguments.

For example:

@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

Upvotes: 2

Views: 97

Answers (2)

stuckoverflow
stuckoverflow

Reputation: 712

See if this simple approach works for you.

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)

Upvotes: 2

4xy
4xy

Reputation: 3662

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)

Upvotes: 1

Related Questions