python - 使用 Python C API 命名参数?

标签 python c python-c-api named-parameters

如何使用 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!

)

最佳答案

参见 the docs : 你想使用 PyArg_ParseTupleAndKeywords,记录在我给的 URL 中。

例如:

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

关于python - 使用 Python C API 命名参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1884327/

相关文章:

将数组中的元素 i 复制到另一个数组

c - recv:连接被对等方重置

python - 格式化 float 列表

python - python 迭代两个数组的快速方法

c - 使用 Tcl C API 的 Lib 崩溃,可能是由于错误的 refCount 使用

python - 如何从多维缓冲区初始化 NumPy 数组?

python - 在 python 中使用 C 扩展,而不将其安装为模块

python - 递增 Py_True/Py_False refcount 总是必要的吗?

python - 检查程序是否在 Debug 模式下运行

python - 有没有一种更优雅的方法可以将字典的键和值解包到两个列表中,而又不会失去一致性?