2009-12-10 4 views
4

Comment puis-je simuler la fonction Python suivante à l'aide de l'API Python C?Paramètres nommés avec API Python C?

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

(à savoir, de sorte qu'il est possible d'appeler via:

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

)

Répondre

11

Voir the docs: vous voulez utiliser PyArg_ParseTupleAndKeywords, documenté à l'adresse que j'ai donné.

Ainsi, par exemple:

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

devient (à peu près - ont pas testé!):

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