Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling function with optional arguments with PyObject_CallMethod

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!

like image 582
lwxted Avatar asked Mar 11 '15 22:03

lwxted


People also ask

How do you pass an optional argument in Python?

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.

How do you pass multiple optional arguments in Python?

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.

Can a function with only keyword arguments be called without 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.

How do you call a function without an argument in Python?

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.


1 Answers

Calling with keyword arguments is not that straightforward from C, and you need to do PyObject_Call, which requires 3 arguments:

  1. The first argument of PyObject_Call is the method object
  2. The second argument of PyObject_Call is the empty tuple for *args
  3. The third argument is the keyword dictionary

Thus 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).

like image 119