Writing a CPython extension - calling another sibbling method ?
MRAB
python at mrabarnett.plus.com
Mon Nov 18 16:11:02 EST 2019
On 2019-11-18 20:15, R.Wieser wrote:
> MRAB,
>
>> One possibility is to refactor the code so that py_proc1 and py_proc2
>> themselves just handle their arguments and then call the function that
>> does the actual work.
>
> The thing is that the arguments of py_proc1 and py_proc2 are the same, but
> for a single argument. Which means that letting both of them first parse
> their own arguments means duplicated code. Which I do not really want and
> thus try to evade
>
> But yes, that is a possibility too. The "the function that does the actual
> work" part is what I tried to describe with my second example.
>
>> A clunkier way would be to make a new tuple that consists of the prepended
>> item and the items of args and pass that to py_proc1 as its args.
>
> That is what I tried to describe with my first example.
>
> The thing is I have no clue about what the above calling should look like
> (though I think I already found how to append my argument to the "args"
> string-object).
>
> In other words, do you have any idea of what either of those calling methods
> should look like ? An example perhaps ? Having only encountered the
> CPython API two days ago I'm still fumbling in the dark I'm afraid.
>
It could be something like this:
static PyObject *py_proc2(PyObject *self, PyObject *args)
{
/*** TODO: Add error checking. ***/
PyObject* prepend_arg;
PyObject* prepend_tuple;
PyObject* new_args;
PyObject* result;
/* The object to be prepended. */
prepend_arg = PyUnicode_FromString("foo");
/* Make a tuple from the prepended object. */
prepend_tuple = BuildValue("(O)", prepend_arg);
/* No longer need prepend_arg. */
Py_DECREF(prepend_arg);
/* Make the new argument list. */
new_args = PySequence_Concat(prepend, args);
/* No longer need prepend_tuple. */
Py_DECREF(prepend_tuple);
/* Call the other method. */
result = py_proc1(self, new_args);
/* No longer need new_args. */
Py_DECREF(new_args);
return result;
}
More information about the Python-list
mailing list