Python C API中的命名参数?

5 投票
1 回答
2121 浏览
提问于 2025-04-15 16:53

我该如何使用Python的C API来模拟下面这个Python函数呢?

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

(也就是说,能够通过以下方式调用它:

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

1 个回答

12

请查看这个文档:你需要使用PyArg_ParseTupleAndKeywords,具体内容可以在我提供的链接中找到。

举个例子:

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

大致上会变成(我还没测试过!):

#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);
}

撰写回答