I am trying to figure out how to use python decorators and I am trying to do so by creating my own version of the timeit
command used to time a function call. This code is working
def mytimeit(f):
def wrapper(*args, **kwargs):
start = time.time()
result = f(*args, **kwargs)
print(f"Function took {time.time() - start} seconds to run.")
return result
return wrapper
@mytimeit
def simple_loop(n=10, sleep=0.2):
for i in range(n):
time.sleep(sleep)
What I want to do now is to somehow pass a parameter to that decorator. I've seen it done and it looks like I have to wrap my decorator in another function, but I cannot get that to work and I am not really sure why.
This is what I have
def mytimeit_with_args(stuff_to_print):
def decorator(f):
def func(*args, **kwargs):
start = time.time()
result = f(*args, **kwargs)
print(stuff_to_print)
print(f"Function took {time.time() - start} seconds to run.")
return result
return func
@mytimeit_with_args("just some stuff")
def harder_loop(n=10, sleep=0.2):
for i in range(n):
time.sleep(sleep)
The error I am getting is TypeError: 'NoneType' object is not callable
What am I not doing correctly?
You are actually really really close. The reason you are getting that error is because you are not returning anything at the very end of the mytimeit_with_args
function, hence the NoneType is not callable error. You just need to add one return statement at the end of mytimeit_with_args
like so
def mytimeit_with_args(stuff_to_print):
def decorator(f):
def func(*args, **kwargs):
start = time.time()
result = f(*args, **kwargs)
print(stuff_to_print)
print(f"Function took {time.time() - start} seconds to run.")
return result
return func
return decorator
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.