简体   繁体   English

使用Boost-Python查找函数具有的参数数量

[英]Use Boost-Python to Find Number of Arguments that Function Have

I have a user-defined function in python which I don't know how many arguments it has. 我在python中有一个用户定义的函数,我不知道它有多少个参数。 ie 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? 如何使用Boost-Python查找该函数有多少个参数? If I just had 1 function argument, I could always evaluate like this: 如果我只有1个函数参数,那么我总是可以这样评估:

  bp::object f1 = main_dict["f1"];
  std::cout << bp::extract<double>(f1(0.0)) << std::endl;

For user-defined functions in python, it is possible to extract the arity of a function through the func_code special attribute. 对于python中的用户定义函数,可以通过func_code特殊属性提取函数的arity This attribute represents the compiled function body, and provides a co_argcount attribute indicating the function's arity. 此属性表示已编译的函数主体,并提供了一个co_argcount属性,用于指示函数的co_argcount For more information and other possible approaches, consider reading this question. 有关更多信息和其他可能的方法,请考虑阅读问题。

Ignoring error checking, the Boost.Python implementation becomes fairly trivial: 忽略错误检查,Boost.Python实现变得相当琐碎:

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
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). 参数列表中的*args将参数列表中未明确定义的所有其他参数分配给列表args (此名称是用户定义的)。 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. 免责声明:我对Boost.Python没有任何经验。 This answer is merely the implementation in Python and transferring the return value into C++ is up to the user. 这个答案仅仅是Python中的实现,将返回值转换为C ++取决于用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM