The simpliest way to wrap a function
func(*args, **kwargs)
... is to manually write a wrapper that would call func() inside itself:
def wrapper(*args, **kwargs):
# do something before
try:
return func(*a, **kwargs)
finally:
# do something after
In Python function is an object, so you can pass it's name as an argument of another function and return it. You can also write a wraper generator for any function anyFunc():
def wrapperGenerator(anyFunc, *args, **kwargs):
def wrapper(*args, **kwargs):
try:
# do something before
return anyFunc(*args, **kwargs)
finally:
#do something after
return wrapper
Please also note that in Python when you don't know or don't want to name all the arguments of a function you can refer to a tuple of arguments, which is denoted by its name preceded by an asterisk in the parentheses after the function name:
*args
For example you can define a function that would take any number of arguments:
def testFunc(*args):
print args # prints the tuple of arguments
Python provides for even funther manipulation on function arguments. You can allow a function to take keyword arguments. Within the function body the keyword arguments are held in a dictionary. In the parentheses arter the function name this dictionary is denoted by two asterisks followed by the name of the dictionary:
**kwargs
A similar example that prints the keyword arguments dictionary:
def testFunc(**kwargs):
print kwargs # prints the dictionary of keyword arguments