Calling an arbitrary function with the right arguments

Chris Rebert 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():
>    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?

Yes; as Steven said, just define the functions so they all have the
same signature in the first place and simply ignore any inapplicable
arguments.

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.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list