Re: Seg fault from PyArg_ParseTuple
Guido.van.Rossum@cwi.nl
Fri, 07 Apr 1995 10:39:24 +0200
> My getattr creates a method on the fly I can't find that method in the
> methodlist of the object:
> 
>       ml = (PyMethodDef *)malloc(sizeof(PyMethodDef));
>       ml->ml_name = strdup(name);
>       ml->ml_meth = pkim_dynamic_kroutine; <--- my meta funtion
>       ml->ml_flags = 0;
>       ml->ml_doc = NULL;
>       return  PyCFunction_New(ml, interface);
> 
> 
> Then inside of pkim_dynamic_kroutine I try and see how I should act
> depending on the number of arguments.  Their are three distinct modes.
> 
> (Os), (O) and ()
> 
> Thus I was (in 1.1.1) doing (something like) this:
> 
> if (PyArg_ParseTuple(args, "Os", &mything, &switches)) {
> 	argumentsOK = TRUE;
> }
> else if (PyArg_Parse(args, "O", &mything)) {
> 	argumentsOK = TRUE;
> }
> else
> 	noArguments = TRUE;
> }
Here the new "optional arguments" feature of PyArg_ParseTuple() helps:
you can make a single call:
	/* Initialize variables to defaults */
	PyObject *mything = NULL;
	char *switches = NULL;
	if (!PyArg_ParseTuple(args, "|Os", &mything, &switches))
		return NULL;
Now if there were no arguments, the variables keep their defaults; if
there was one argument, mything gets that argument and switches is
unchanged; if there were two arguments, both variables are changed.
--Guido van Rossum, CWI, Amsterdam <mailto:guido@cwi.nl>
<http://www.cwi.nl/~guido/>