Expand tuple into argument list?
Fredrik Lundh
fredrik at pythonware.com
Wed Jul 14 21:20:52 EDT 1999
Steven Work <steve at renlabs.com> wrote:
> I'm new to Python. I want a dispatch function -- takes a function
> name and other arguments, calls the named function with the remaining
> arguments. This works for limited length argument lists:
>
> def dispatch(fnname, *rest):
> fn = dispatch.func_globals[fnname]
> if len(rest)==0:
> return fn()
> elif len(rest)==1:
> return fn(rest[0])
> elif len(rest)==2:
> return fn(rest[0], rest[1])
> elif len(rest)==3:
> return fn(rest[0], rest[1], rest[2])
> elif len(rest)==4:
> return fn(rest[0], rest[1], rest[2], rest[3])
>
> but is there a general way to expand the tuple into an argument list?
http://www.python.org/doc/FAQ.html#4.31
"How do I call a function if I have the arguments in a tuple?"
...
in your case, something like:
function = global()[fnname]
result = apply(function, arguments)
should do the trick. you can pass a dictionary with
keyword arguments as a third argument to apply. see
the built-in functions section in the library reference
for more info.
</F>
More information about the Python-list
mailing list