Benannte Parameter mit Python-C-API?
-
19-09-2019 - |
Frage
Wie kann ich die folgende Python-Funktion mit dem Python-C-API simulieren?
def foo(bar, baz="something or other"):
print bar, baz
(das heißt, so dass es möglich ist, es zu nennen über:.
>>> foo("hello")
hello something or other
>>> foo("hello", baz="world!")
hello world!
>>> foo("hello", "world!")
hello, world!
)
Lösung
Siehe die docs : Sie wollen verwenden PyArg_ParseTupleAndKeywords
, unter der URL dokumentiert ich gegeben habe.
So zum Beispiel:
def foo(bar, baz="something or other"):
print bar, baz
wird (! Grob - habe es nicht getestet):
#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);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow