Using Python C API, how can I call a function with optional arguments?
For example, assuming there is a Python module add_module.py
with a function add
that goes like:
def add(a=0, b=0):
return a + b
add(1, 2)
would correspond to
PyObject *add_module = PyImport_ImportModule("add_module");
PyObject *result = PyObject_CallMethod(add_module, "add", "ii", 1, 2);
How would I call something like add(b=5)
using the Python API?
Thanks!
You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.
Using Python optional arguments using **kwargs The ** allows us to pass any number of keyword arguments. The main difference between single asterisk *args and double **kwargs is that the *args contain non-keyword arguments while **kwargs contains keyword arguments.
With keyword arguments, as long as you assign a value to the parameter, the positions of the arguments do not matter. However, they do have to come after positional arguments and before default/optional arguments in a function call.
7.1. A function without an explicit return statement returns None . In the case of no arguments and no return value, the definition is very simple. Calling the function is performed by using the call operator () after the name of the function.
Calling with keyword arguments is not that straightforward from C, and you need to do PyObject_Call
, which requires 3 arguments:
PyObject_Call
is the method objectPyObject_Call
is the empty tuple for *argsThus we get
PyObject *function = PyObject_GetAttrString(add_module, "add");
PyObject *args = PyTuple_New(0);
PyObject *kwargs = Py_BuildValue("{s:i}", "b", 5)
result = PyObject_Call(function, args, kwargs);
Py_DECREF(kwargs);
Py_DECREF(args);
Py_DECREF(function);
except you must NULL-check the return values from the 4 first functions (omitted for brevity).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With