Handling variable number of arguments.

Jim Meier fatjim at home.com
Thu Jun 3 12:23:58 EDT 1999


bhosu at my-deja.com wrote:

> Hi All,
>    I am embedding Python in an application(C++). I would like to pass
> variable number of args to the python function. I could do that from
> python by using def foo(*args). How do I parse these arguments inside my
> application? In PyARg_ParseTuple, I have to know exactly how many args
> to read etc. I am using Python v 1.4. I was looking at
> PyArg_ParseTupleAndKeywords but that needs the args to be a dictionary.
> I am looking a similar thingy for lists. A typeical scenario of the
> usage is like,
> import foo
> foo.set_args('bar','=','1','2','3')
>
> where foo is the module containing the method implementation.

PyArg_ParseTuple supports optional arguments:

int a,b,c,d,e,f,how_many;
if(!PyArg_ParseTuple("ii|iiii",a,b,c,d,e,f)) return NULL;
how_many=PyTuple_Size(args);

So you could use that if you simply have a known number of optional extra
arguments. See "Extending and Embedding", section 1.7 "Format Strings for
PyArg_ParseTuple". Otherwise, if you need a varying number of arguments
(only really possible if you are calling the function with apply()), do as
Michael P. Reilly's response suggests (access args as a tuple directly).

Hope that helps,
-Jim.





More information about the Python-list mailing list