C API with *args and **kw

M

Miki

Hello All,

I'm try to write the C equivalent of:

def kw(*args, **kw):
print "%d args" % len(args),
if "default" in kw:
print "default is %s" % kw["default"]
else:
print "no default"

I've written:
static PyObject *
kw(PyObject *self, PyObject *args, PyObject *kwds) {
PyObject *defval = NULL;
long nargs;
char *str;

nargs = PyTuple_GET_SIZE(args);
printf("%d args ", nargs);

defval = PyDict_GetItemString(kwds, "default");

if (NULL == defval) {
printf("no default\n");
}
else {
str = PyString_AsString(defval);
printf("default is %s\n", str);
}

return Py_BuildValue("");
}

However when running the test:
from kw import kw
kw(default="2")
kw(1)
kw()

I get "bus error" on the 2'nd call (OS X Python 2.5.2).

Any idea?

TIA,
 
S

Stefan Behnel

Miki said:
I'm try to write the C equivalent of:

def kw(*args, **kw):
print "%d args" % len(args),
if "default" in kw:
print "default is %s" % kw["default"]
else:
print "no default"

Consider using Cython instead, it will make your life a lot easier. The above
is valid Cython code that the Cython compiler translates into optimised C code.

http://cython.org/

Stefan
 
M

Miki

I'm try to write the C equivalent of:
Use PyArg_ParseTupleAndKeywords() to parse the args and kwargs objects.
Couldn't figure out how to get *args with ParseTupleAndKeywords.

Thanks,
Miki
 
M

Miki

Miki said:
When called without keywords, kwds is NULL.  You need to handle that
case explicitly.
Great, thanks!
The equivalent of your Python code would be to return None using
Py_RETURN_NONE (sugar for Py_INCREF(Py_None); return Py_None;).
OK, Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top