Reputation: 250
Say I have two functions:
def a(name = None):
return "Hello " + name
def b(say = "something"):
return "I will say " + say
What the functions do are mostly irrelevant right now. I would just like to know if there is a way to implement a repeat()
function, which will repeat either a()
or b()
depending on which was last executed.
Thank you in advance!
Upvotes: 1
Views: 209
Reputation: 384
You can achieve that using decorators
latest = None
latest_args = None
latest_kwargs = None
def my_decorator():
def decorate(func):
def wrapper(*args, **kwargs):
global latest
global latest_args
global latest_kwargs
latest = func
latest_args = args
latest_kwargs = kwargs
return func(*args, **kwargs)
return wrapper
return decorate
def repeat():
if latest is None:
raise Exception("cannot call repeat without calling a function first")
return latest(*latest_args, **latest_kwargs)
@my_decorator()
def a(name = None):
return "Hello " + name
@my_decorator()
def b(say = "something"):
return "I will say " + say
print(a("Bob"))
print(repeat())
print(b())
print(repeat())
Note that this may not be the best way to do so, it's just the first thing that come on to my mind, essentially, every time you call a decorated function, wrapper()
will be called instead, which will save the function and the arguments, and then, wrapper()
calls the function.
Upvotes: 6