Reputation: 13671
I am wrapping some c++ code using cython, and I am not sure what is the best best way to deal with parameters with default values.
In my c++ code I have function for which the parameters have default values. I would like to wrap these in such a way that these default values get used if the parameters are not given. Is there a way to do this?
At this point the only way that I can see to provide option parameters is to define them as part of the python code (in the def func
satement in pycode.pyx below), but then I have defaults defined more than once which I don't want.
cppcode.h:
int init(const char *address=0, int port=0, int en_msg=false, int error=0);
pycode_c.pxd:
cdef extern from "cppcode.h":
int func(char *address, int port, int en_msg, int error)
pycode.pyx:
cimport pycode_c
def func(address, port, en_msg, error):
return pycode_c.func(address, port, en_msg, error)
Upvotes: 16
Views: 9734
Reputation: 414685
You could declare the function with different parameters ("cppcode.pxd"
):
cdef extern from "cppcode.hpp":
int init(char *address, int port, bint en_msg, int error)
int init(char *address, int port, bint en_msg)
int init(char *address, int port)
int init(char *address)
int init()
Where "cppcode.hpp"
:
int init(const char *address=0, int port=0, bool en_msg=false, int error=0);
It could be used in Cython code ("pycode.pyx"
):
cimport cppcode
def init(address=None,port=None,en_msg=None,error=None):
if error is not None:
return cppcode.init(address, port, en_msg, error)
elif en_msg is not None:
return cppcode.init(address, port, en_msg)
elif port is not None:
return cppcode.init(address, port)
elif address is not None:
return cppcode.init(address)
return cppcode.init()
And to try it in Python ("test_pycode.py"
):
import pycode
pycode.init("address")
address 0 false 0
Cython also has arg=*
syntax (in *.pxd
files) for optional parameters:
cdef foo(x=*)
Upvotes: 18