It is Pythonic to use None
as the default for an optional argument. For example, use None
as the default of a string argument:
def f(str_arg=None):
if str_arg is None:
str_arg = get_str_arg_default()
...
Thus f()
accepts two types for argument str_arg
: a string or None
.
Now, we are implementing this function in C++ using Boost Python. How do I make Boost Python accept both string and None
types for an argument?
Can you have the function accept a boost::python::object
? Then you can check if it is None
by calling is_none()
.
See https://wiki.python.org/moin/boost.python/FAQ#How_can_I_check_returning_Python_value_for_None.3F which gives several suggestions for checking if an object is None
- e.g. arg.ptr() == object().ptr()
, arg.ptr() == Py_None
or arg.is_none()
.