使用 pybind11 包装 yaml-cpp 迭代器



我正在尝试用pybind11包装一些yaml-cpp代码。我意识到有一个用于操作yaml文件的python模块,但我希望对这种方法有所帮助。我只是想熟悉pybind11。

具体来说,我想将迭代器包装为YAML::Node,但是迭代器的返回类型不是YAML::Node,而是YAML::detail::iterator_value。如何从此类型返回到迭代器 lambda 函数中的YAML::Node?以下是我的代码的相关部分。

utilities_py.cc

#include "yaml-cpp/yaml.h"
#include "pybind11/pybind11.h"
PYBIND11_MODULE(utilities, m) {
namespace py = pybind11;
py::class_<YAML::detail::iterator_value>(m, "YamlDetailIteratorValue")
.def(py::init<>());
py::class_<YAML::Node>(m, "YamlNode")
.def(py::init<const std::string &>())
.def("__getitem__",
[](const YAML::Node node, const std::string key){
return node[key];
})
.def("__iter__",
[](const YAML::Node &node) {
return py::make_iterator(node.begin(), node.end());},
py::keep_alive<0, 1>());
m.def("load_file", &YAML::LoadFile, "");
}

test_utilities_py.py

from utilities import load_file
test_node = load_file('test.yaml')
for nodelette in test_node:
prop = nodelette['prop']

我收到以下错误:

TypeError: __getitem__: incompatible function arguments. The following argument types are supported:
1. (arg0: utilities.YamlNode, arg1: str) -> utilities.YamlNode
Invoked with: <utilities.YamlDetailIteratorValue object at 0x7f8babc446f0>, 'prop'

你很接近。如果你看一下源代码,YAML::detail::iterator_value扩展YAML::Node,所以你必须在python代码中考虑到这一点。它也扩展了std::pair<YAML::Node, YAML::Node>,所以这也需要以某种方式加以考虑。

struct iterator_value : public Node, std::pair<Node, Node> {

当它被绑定时,我们必须确保 Node 被绑定为父类。这将看起来像:

py::class_<YAML::detail::iterator_value, YAML::Node>(m, "YamlDetailIteratorValue")

现在,当您迭代时,您拥有了所有 Node 方法,这很好!但是你会遇到真正的麻烦,因为iterator_value也继承了std::pair。据我所知,没有办法在 pybind11 中仅将其用作父类型,即使它具有对的自动转换(有bind_vectorbind_map但没有bind_pair(。我认为你可以为这样的事情编写自己的绑定,但我不确定这是必要的。实际上,您需要做的是检查要迭代的Node的类型,然后根据它是映射还是序列进行稍微不同的迭代(这类似于C ++ API的工作方式,其中序列和映射都有一个迭代器类型, 但是如果在错误的上下文中调用某些函数将失败(。

以下是我最终解决问题的方式:

PYBIND11_MODULE(utilities, m) {
py::enum_<YAML::NodeType::value>(m, "NodeType")
.value("Undefined", YAML::NodeType::Undefined)
.value("Null", YAML::NodeType::Null)
.value("Scalar", YAML::NodeType::Scalar)
.value("Sequence", YAML::NodeType::Sequence)
.value("Map", YAML::NodeType::Map);
py::class_<YAML::Node>(m, "YamlNode")
.def(py::init<const std::string &>())
.def("__getitem__",
[](const YAML::Node node, const std::string& key){
return node[key];
})
.def("__iter__",
[](const YAML::Node &node) {
return py::make_iterator(node.begin(), node.end());},
py::keep_alive<0, 1>())
.def("__str__",
[](const YAML::Node& node) {
YAML::Emitter out;
out << node;
return std::string(out.c_str());
})
.def("type", &YAML::Node::Type)
.def("__len__", &YAML::Node::size)
;
py::class_<YAML::detail::iterator_value, YAML::Node>(m, "YamlDetailIteratorValue")
.def(py::init<>())
.def("first", [](YAML::detail::iterator_value& val) { return val.first;})
.def("second", [](YAML::detail::iterator_value& val) { return val.second;})
;
m.def("load_file", &YAML::LoadFile, "");

我绑定了 NodeType 枚举,因此当您在节点上调用type时可以公开它。然后,我绑定了iterator_value类型的firstsecond,以便您可以循环访问映射值。您可以打开type()以弄清楚如何迭代。我的示例 yaml 文件

---
doe: "a deer, a female deer"
ray: "a drop of golden sun"
pi: 3.14159
xmas: true
french-hens: 3
calling-birds:
- huey
- dewey
- louie
- fred
xmas-fifth-day:
calling-birds: four
french-hens: 3
golden-rings: 5
partridges:
count: 1
location: "a pear tree"
turtle-doves: two

以及我使用绑定 c++ 的示例 python (3.8( 代码

import example
from example import load_file
def iterator(node):
if node.type() == example.NodeType.Sequence:
return node
elif node.type() == example.NodeType.Map:
return ((e.first(), e.second()) for e in node)
return (node,)
test_node = load_file('test.yml')

for key, value in iterator(test_node):
if value.type() == example.NodeType.Sequence:
print("list")
for v in iterator(value):
print(v)
elif value.type() == example.NodeType.Map:
print("map")
for k,v in iterator(value):
temp = value[str(k)]
print(k, v)
print(str(v) == str(temp))

演示不同类型的正确迭代,以及__get__在地图上的工作方式与在iterator_value上调用.second时一样好的事实。您可能希望覆盖 ints 上的__get__,因此它也允许您进行序列访问。

您还有一个额外的__str__方法,可以使所有print调用正常工作。

最新更新