Calling an arbitrary function with the right arguments

Peter Otten __peter__ at web.de
Mon Sep 27 10:42:02 CEST 2010


John O'Hagan wrote:

> How to call a function with the right arguments without knowing in advance
> which function? For example:
> 
> import random
> 
> def f1():
>     pass
> 
> def f2(foo):
>     pass
> 
> def f3(foo, bar):
>     pass
> 
> foo=random.choice((1,2,3))
> bar=random.choice((1,2,3))
> 
> myfunc=random.choice((f1, f2, f3))
> 
> How to call myfunc with the right arguments?
> I've been doing it this way:
> 
> f1.args=()
> f2.args=('foo',)
> f3.args=('foo', 'bar')
> 
> args=[vars()[i] for i in myfunc.args]
> 
> myfunc(*args)
> 
> But it seems redundant to manually tag the functions with their own
> arguments' names, and I don't like using vars(). Is there a nicer pattern?

You can use inspect.getargspec() to determine the argument names:

args = [vars()[argname] for argname in inspect.getargspec(myfunc).args]





More information about the Python-list mailing list