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;
2
  • 1
    Do you specifically need Boost-Python? If not, just use *args and find the length of that Commented Jan 6, 2013 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? Commented Jan 6, 2013 at 19:22

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.