Expand tuple into argument list?
Michael P. Reilly
arcege at shore.net
Wed Jul 14 21:24:03 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?
: (I know about keyword arguments already.)
: Lest you ask why: I'm embedding a Python interpreter in a C program; I
: need to call Python functions directly from C, and I'd like a single
: point of contact to minimize the required housekeeping.
Inside Python you can replace the if-elif construct with apply:
def dispatch(fnname, *rest):
fn = dispatch.func_globals[fnname]
return apply(fn, rest)
But from C, you will want to use PyObject_CallObject:
result = PyObject_CallObject(fn, args);
(http://www.python.org/doc/current/api/object.html)
-Arcege
More information about the Python-list
mailing list