我正在尝试在boost :: python中创建一个Python迭代器。所以我有一个功能
PyObject *my_iterator_next(MyIterator *iter) {
if (!iter->is_end()) {
return *(*iter)++;
}
else {
PyErr_SetNone(PyExc_StopIteration);
// this doesn't work either
// PyErr_SetString(PyExc_StopIteration, "end of collection");
return NULL;
}
}
在Python中:
// x is MyContainer([1, 2, 3])
for x in my_container:
print(x)
我得到了:
1
2
3
NoneTraceback (most recent call last):
File "main.py", line 6, in <module>
print(x)
StopIteration: end of collection
另外
it = my_collection.__iter__()
try:
it.__next__();
it.__next__();
it.__next__();
it.__next__();
except:
print("caught exception")
此代码不会打印任何内容,因此不会捕获任何类型的异常。
为什么?
答案 0 :(得分:2)
设置Python异常后,必须像这样通知Boost.Python:
throw_error_already_set();
请参阅http://www.boost.org/doc/libs/1_35_0/libs/python/doc/v2/errors.html