keywords for optional args in extension modules

S

Sean Richards

Python 2.3.4 (#1, May 29 2004, 17:05:23)
[GCC 3.3.3] on linux2

Getting some strange behaviour with keyword arguments for optional
arguments in extension modules. See the simple test case below

--------8<--------------------------------------------------
#include "Python.h"

static PyObject *
keywdarg_test(PyObject *self, PyObject *args, PyObject *keywds)
{
int one;
unsigned int two = 2;
int three = 3;

static char *kwlist[] = {"one", "two", "three", NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|Ii", kwlist,
&one, &two, &three))
return NULL;

Py_INCREF(Py_None);
return Py_None;
}

static PyMethodDef keywdarg_methods[] = {
{"test", (PyCFunction)keywdarg_test, METH_VARARGS | METH_KEYWORDS},
{NULL, NULL, 0, NULL}
};

void
initkeywdarg(void)
{
Py_InitModule("keywdarg", keywdarg_methods);
}
--------8<--------------------------------------------------

Compile the module

$ cc -g -c keywdarg.c -I/usr/include/python2.3
$ ld -shared -o keywdarg.so keywdarg.o


Test it

In [1]: from keywdarg import *

In [2]: test(1)

In [3]: test(1,two=2)

In [4]: test(1,two=2,three=3)

In [5]: test(1,three=3,two=2)

In [6]: test(1,three=3)
---------------------------------------------------------------------------
exceptions.TypeError Traceback (most recent call last)

/home/sean/research/code/framework/wiener/<console>

TypeError: argument 2, item 1074941247, item 1079307903 impossible<bad format char>


However if I change the order of the optional arguments so the unsigned
int is last as below then it works fine.

if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|iI", kwlist,
&one, &three, &two))


This seems buggy. Python 2.3 is getting a bit old now but do later later
versions still exhibit this behaviour?

Cheers, Sean
 

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

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,833
Latest member
BettyeMacf

Latest Threads

Top