I like being able to measure performance of the python functions I code, so very often I do something similar to this…
import time
def some_function(arg1, arg2, ..., argN, verbose = True) :
t = time.clock() # works best in Windows
# t = time.time() # apparently works better in Linux
# Function code goes here
t = time.clock() - t
if verbose :
print "some_function executed in",t,"sec."
return return_val
Yes, I know you are supposed to measure performance with timeit, but this works just fine for my needs, and allows me to turn this information on and off for debugging very smoothly.
That code of course was from before I knew about function decorators… Not that I know much about them now, but I think I could write a decorator that did the following, using the **kwds dictionary:
some_function(arg1, arg2, ..., argN) # Does not time function
some_function(arg1, arg2, ..., argN, verbose = True) # Times function
I would nevertheless like to duplicate the prior working of my functions, so that the working would be something more like:
some_function(arg1, arg2, ..., argN) # Does not time function
some_function(arg1, arg2, ..., argN, False) # Does not time function
some_function(arg1, arg2, ..., argN, True) # Times function
I guess this would require the decorator to count the number of arguments, know how many the original function will take, strip any in excess, pass the right number of them to the function… I’m uncertain though on how to tell python to do this… Is it possible? Is there a better way of achieving the same?
Though inspect may get you a bit on the way, what you want is in general not possible:
Now how many arguments does
ftake? Since*argsand**kwargsallow for an arbitrary number of arguments, there is no way to determine the number of arguments a function requires. In fact there are cases where the function really handles as many as there are thrown at it!Edit: if you’re willing to put up with
verboseas a special keyword argument, you can do this:(Thanks Alex Martelli for the
kwargs.poptip!)