Calling an arbitrary function with the right arguments
John O'Hagan
research at johnohagan.com
Sun Sep 26 23:41:13 EDT 2010
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?
Regards,
John
More information about the Python-list
mailing list