0

I have a user-defined function in python which I don't know how many arguments it has. i.e. It can be

def f1(x,y,z):
  return  sin(x)*cos(y)*tan(z)

or

def f1(x):
  return  sin(x)

How I can use Boost-Python to find how many arguments the function has? If I just had 1 function argument, I could always evaluate like this:

  bp::object f1 = main_dict["f1"];
  std::cout << bp::extract<double>(f1(0.0)) << std::endl;
Roy
  • 65
  • 2
  • 15
  • 40
  • 1
    Do you specifically need **Boost-Python**? If not, just use `*args` and find the length of that – Volatility Jan 06 '13 at 10:39
  • I want to get access to the number of arguments of python function in C++. How I can use args to do that? – Roy Jan 06 '13 at 19:22

2 Answers2

2

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
Community
  • 1
  • 1
Tanner Sansbury
  • 51,153
  • 9
  • 112
  • 169
1
def foobar(x, *args):
    return len(args) + 1

The *args in the parameter list assigns all extra arguments not explicitly defined in the paramater list to a list args (this name is user-defined). Assuming the function must have at least one parameter, the above function will return the number of arguments.

Disclaimer: I have no experience whatsoever with Boost.Python. This answer is merely the implementation in Python and transferring the return value into C++ is up to the user.

Volatility
  • 31,232
  • 10
  • 80
  • 89
  • If I understand the question correctly, the question is about finding the arity of a function (i.e. how many arguments does `foobar` accept), and not the count of invocation arguments (i.e. `len(args) + 1`). – Tanner Sansbury Jan 07 '13 at 14:31