使用Python C API命名参数?

Mic*_*ael 4 c python named-parameters python-c-api

如何使用Python C API模拟以下Python函数?

def foo(bar, baz="something or other"):
    print bar, baz
Run Code Online (Sandbox Code Playgroud)

(即,可以通过以下方式调用它:

>>> foo("hello")
hello something or other
>>> foo("hello", baz="world!")
hello world!
>>> foo("hello", "world!")
hello, world!
Run Code Online (Sandbox Code Playgroud)

)

Ale*_*lli 11

请参阅文档:您要使用的PyArg_ParseTupleAndKeywords文档,记录在我提供的URL中.

例如:

def foo(bar, baz="something or other"):
    print bar, baz
Run Code Online (Sandbox Code Playgroud)

变得(粗略 - 没有测试过!):

#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);
}
Run Code Online (Sandbox Code Playgroud)