For user-defined functions in python, it is possible to extract the arity of a function through the func_code
special attribute. This attribute represents the compiled function body, and provides a co_argcount
attribute indicating the function's arity. For more information and other possible approaches, consider reading this question.
Ignoring error checking, the Boost.Python implementation becomes fairly trivial:
boost::python::extract<std::size_t>(fn.attr("func_code").attr("co_argcount"));
Here is a complete brief example:
#include <iostream>
#include <boost/python.hpp>
void print_arity(boost::python::object fn)
{
std::size_t arity = boost::python::extract<std::size_t>(
fn.attr("func_code").attr("co_argcount"));
std::cout << arity << std::endl;
}
BOOST_PYTHON_MODULE(example)
{
def("print_arity", &print_arity);
}
And its usage:
>>> from example import print_arity
>>> def f1(x,y,z): pass
...
>>> print_arity(f1)
3
>>> def f1(x): pass
...
>>> print_arity(f1)
1