从boost :: python中的kwargs中提取参数

ore*_*ago 7 c++ python kwargs boost-python

我有一个C++类,我正在使用boost :: python构建一个python模块.我有一些函数,我想采取关键字参数.我已经设置了包装函数来传递给raw_arguments,并且工作正常,但我想构建一些函数参数的错误检查.有没有标准的方法来做到这一点?

我的函数原型,在C++中,看起来有点像这样:

double MyClass::myFunction(int a, int b, int c);
Run Code Online (Sandbox Code Playgroud)

第三个参数是可选的,默认值为0(到目前为止,我已经使用宏在boost :: python中实现了这个).在python中,我希望能够实现以下行为:

MyClass.my_function(1) # Raises exception
MyClass.my_function(2, 3) # So that a = 2, b = 3 and c defaults to 0
MyClass.my_function(2, 3, 1) # As above, but now c = 1
MyClass.my_function(2, 3, 1, 3) # Raises exception
MyClass.my_function(3, 1, c = 2) # So a = 3, b = 1 and c = 2
MyClass.my_function(a = 2, b = 2, c = 3) # Speaks for itself
MyClass.my_function(b = 2, c = 1) # Raises exception
Run Code Online (Sandbox Code Playgroud)

boost :: python或raw_function包装器中有什么东西可以促进这一点,或者我是否需要编写代码来自行检查所有这些?如果我确实需要,我该如何提出异常?有这样做的标准方法吗?

Tan*_*ury 14

boost/python/args.hpp文件提供了一系列用于指定参数关键字的类.特别是,Boost.Python提供了一个arg表示潜在关键字参数的类型.它会重载逗号运算符,以允许更自然地定义参数列表.

暴露myFunctionMyClassmy_function,其中a,bc是关键字参数,并且c有一个默认值0可以写成如下:

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<MyClass>("MyClass")
    .def("my_function", &MyClass::myFunction,
         (python::arg("a"), "b", python::arg("c")=0))
    ;
}
Run Code Online (Sandbox Code Playgroud)

这是一个完整的例子:

#include <boost/python.hpp>

class MyClass
{
public:
  double myFunction(int a, int b, int c)
  {
    return a + b + c;
  }
};

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<MyClass>("MyClass")
    .def("my_function", &MyClass::myFunction,
         (python::arg("a"), "b", python::arg("c")=0))
    ;
}
Run Code Online (Sandbox Code Playgroud)

互动用法:

>>> import example
>>> my_class = example.MyClass()
>>> my_class.my_function(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
    MyClass.my_function(MyClass, int)
did not match C++ signature:
    my_function(MyClass {lvalue}, int a, int b, int c=0)
>>> assert(5 == my_class.my_function(2, 3))
>>> assert(6 == my_class.my_function(2, 3, 1))
>>> my_class.my_function(2, 3, 1, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
    MyClass.my_function(MyClass, int, int, int, int)
did not match C++ signature:
    my_function(MyClass {lvalue}, int a, int b, int c=0)
>>> assert(6 == my_class.my_function(3, 1, c=2))
>>> assert(7 == my_class.my_function(a=2, b=2, c=3))
>>> my_class.my_function(b=2, c=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
    MyClass.my_function(MyClass)
did not match C++ signature:
    my_function(MyClass {lvalue}, int a, int b, int c=0)
Run Code Online (Sandbox Code Playgroud)