3

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?

2 Answers 2

8

Just call the function like this:

fn(*args)
Sign up to request clarification or add additional context in comments.

3 Comments

Sweet capers that was quick. Just tried and it worked. Thanks!
+1 and for further reading, saltycrane.com/blog/2008/01/…
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)
2

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.

2 Comments

Just curious, why are you timing the print as well as the function?
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.