Whether The Return Value Of A Function Modified By Python Decorator Can Only Be Nonetype
I wrote a decorator that gets the runtime of the program, but the function return value becomes Nonetype. def gettime(func): def wrapper(*args, **kw): t1 = time.time()
Solution 1:
Since the wrapper replaces the function decorated, it also needs to pass on the return value:
def wrapper(*args, **kw):
t1 = time.time()
ret = func(*args, **kw) # save it here
t2 = time.time()
t = (t2-t1)*1000
print("%s run time is: %.5f ms"%(func.__name__, t))
return ret # return it here
Solution 2:
Or you can do:
def gettime(func):
def wrapper(*args, **kw):
t1 = time.time()
func(*args, **kw)
t2 = time.time()
t = (t2-t1)*1000
print("%s run time is: %.5f ms"%(func.__name__, t))
print("The correct rate is: %f"%func(*args,**kw))
return wrapper
@gettime
def contrast(a, b):
res = np.sum(np.equal(a, b))/a.size
return res
contrast(A,B)
Post a Comment for "Whether The Return Value Of A Function Modified By Python Decorator Can Only Be Nonetype"