Calling an arbitrary function with the right arguments
Steven D'Aprano
steve-REMOVE-THIS at cybersource.com.au
Mon Sep 27 00:10:46 EDT 2010
On Mon, 27 Sep 2010 03:41:13 +0000, 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?
If f1, f2 and f3 require different arguments, it's not sensible to expect
them to be interchangeable. The right way to do this is to re-write the
functions so they all have the same call signature (even if that is just
to ignore unnecessary arguments). Or wrap the functions (perhaps using
functools.partial) so they don't need the extra args.
f3 = lambda f=f3: f(foo, bar)
f2 = lambda f=f2: f(foo)
Either way, there's a reason you never see callback functions that accept
arbitrary arguments. They always have a standard, fixed argument list.
--
Steven
More information about the Python-list
mailing list