tags:

views:

156

answers:

2

I'd like an easy way to plug in a function and arguments to be executed later so I can have a kind of wrapper around it.

In this case, I'd like to use it to benchmark, example:

def timefunc(fn, *args):
   start = time.clock()
   fn(args)
   stop = time.clock()
   return stop - start

How do I pass arguments where the number of parameters aren't known? How do I find the number of parameters? How would I even call the function once I knew the number of parameters?

+6  A: 

Just call the function like this:

fn(*args)
MatrixFrog
Sweet capers that was quick.Just tried and it worked. Thanks!
emcee
+1 and for further reading, http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
Graphics Noob
For completeness, even though you didn't ask about it, note that if your function takes keyword arguments `timefunc(fn, *args, **kwargs)`, you can plug them into another function the same way: `fn(*args, **kwargs)`
Chris Lutz
A: 

MatrixFrog's answer is the correct one, but just to complete the picture. For finding out the number of arguments simply call len, because args is a tuple:

import time

def timefunc(fn, *args):
   start = time.clock()
   print len(args), type(args)
   fn(*args)
   stop = time.clock()
   return stop - start


def myfoo(a, b):
    c = a + b
    return c


timefunc(myfoo, 5, 6)

The print statement inside timefunc prints:

2 <type 'tuple'>

Since args is a tuple, you can access it like any other tuple.

Eli Bendersky
Just curious, why are you timing the `print` as well as the function?
Chris Lutz
Chris I'm not timing it. I've just inserted it inside the function to show in the simplest way what the length and type of args is. It's just for debugging
Eli Bendersky