Calling an arbitrary function with the right arguments
clp2 at rebertia.com
Mon Sep 27 06:19:23 CEST 2010
On Sun, Sep 26, 2010 at 8:41 PM, John O'Hagan <research at johnohagan.com> wrote:
> How to call a function with the right arguments without knowing in advance
> which function? For example:
> import random
> def f1():
> def f2(foo):
> def f3(foo, bar):
> myfunc=random.choice((f1, f2, f3))
> How to call myfunc with the right arguments?
> I've been doing it this way:
> f3.args=('foo', 'bar')
> args=[vars()[i] for i in 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?
Yes; as Steven said, just define the functions so they all have the
same signature in the first place and simply ignore any inapplicable
However, alternatively, you could use inspect.getargspec()
(http://docs.python.org/library/inspect.html#inspect.getargspec ) to
figure out what arguments each functions needs. I do not actually
recommend this method, but merely mention it for completeness.
More information about the Python-list