I’m developing a package in which I want to modify incoming functions to add extra functionality. I’m not sure how I would go about doing this. A simple example of what I’m trying to do:
def function(argument):
print(argument,end=",")
# this will not work but an attempt at illustrating what I wish to accomplish
def modify_function(original_function):
return def new_function(arguments):
for i in range(3):
original_function(arguments)
print("finished",end="")
and running the original function:
function("hello")
gives the output: hello,
and running the modified function:
modified_function = modify_function(function)
modified_function(i)
gives the output: hello,hello,hello,finished
>Solution :
Credit to @Matiss for pointing out the way to do this. Adding this answer so it is documented.
def original_function(argument):
print(argument, end=",")
def modify_function(input_func):
# Using *args and **kwargs allows handling of multiple arguments
# and keyword arguments, in case something more general is required.
def new_func(*args, **kwargs):
for i in range(3):
input_func(*args, **kwargs)
print("finished", end="")
return new_func
modified_function = modify_function(original_function)
modified_function("hello")
For other kinds of modification where you want to e.g. fix some of the arguments passed in, this way will still work, but you may also make use of https://docs.python.org/3/library/functools.html#functools.partial.