I am trying to write python decorators and I am having problems understanding how the internal wrapper takes arguments. I have here:
import time
def timing_function(some_function):
def wrapper():
t1 = time.time()
some_function()
t2 = time.time()
return "Time it took to run: " + str((t2-t1)) + "\n"
return wrapper
@timing_function
def my_function(x):
return x * x
my_function(6)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-fe2786a2753c> in <module>()
----> 1 my_function(6)
TypeError: wrapper() takes no arguments (1 given)
Which is slightly different than the example:
import time
def timing_function(some_function):
"""
Outputs the time a function takes
to execute.
"""
def wrapper():
t1 = time.time()
some_function()
t2 = time.time()
return "Time it took to run the function: " + str((t2-t1)) + "\n"
return wrapper
@timing_function
def my_function():
num_list = []
for x in (range(0,10000)):
num_list.append(x)
return "\nSum of all the numbers: " +str((sum(num_list)))
print my_function()
Time it took to run the function: 0.0
It seems the problem is the 'x' argument. I tried giving wrapper *args, but it also did not work. My questions are
What is the proper way to allow arguments in this simple wrapper? Thank you
Why do all decorator examples I've seen always have an internal function, can you not write a decorator as one function?
Thank you