开发者

Named parameters with Python C API?

开发者 https://www.devze.com 2022-12-13 15:10 出处:网络
How can I simulate the following Python function using the Python C API? def foo(bar, baz=\"something or other\"):

How can I simulate the following Python function using the Python C API?

def foo(bar, baz="something or other"):
    print bar,开发者_运维百科 baz

(i.e., so that it is possible to call it via:

>>> foo("hello")
hello something or other
>>> foo("hello", baz="world!")
hello world!
>>> foo("hello", "world!")
hello, world!

)


See the docs: you want to use PyArg_ParseTupleAndKeywords, documented at the URL I gave.

So for example:

def foo(bar, baz="something or other"):
    print bar, baz

becomes (roughly -- haven't tested it!):

#include "Python.h"

static PyObject *
themodule_foo(PyObject *self, PyObject *args, PyObject *keywds)
{
    char *bar;
    char *baz = "something or other";

    static char *kwlist[] = {"bar", "baz", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, keywds, "s|s", kwlist,
                                     &bar, &baz))
        return NULL;

    printf("%s %s\n", bar, baz);

    Py_INCREF(Py_None);
    return Py_None;
}

static PyMethodDef themodule_methods[] = {
    {"foo", (PyCFunction)themodule_foo, METH_VARARGS | METH_KEYWORDS,
     "Print some greeting to standard output."},
    {NULL, NULL, 0, NULL}   /* sentinel */
};

void
initthemodule(void)
{
  Py_InitModule("themodule", themodule_methods);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消