2

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
2

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Edit: fixed a small error. Works fine now.
1
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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.