2
我想在boost :: python中做一個Python迭代器。所以我有一個功能爲什麼Python不會捕獲在C++中引發的異常?
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")
這個代碼不打印任何東西,所以沒有發現任何類型的異常。
爲什麼?
如果底層的迭代器是一個C++迭代器,那麼它可以使用['提升價值: :python :: iterator'](http://www.boost.org/doc/libs/1_56_0/libs/python/doc/v2/iterator.html),因爲它處理所有細微的細節(例如具有迭代器延長容器的使用壽命)。這[回答](http://stackoverflow.com/a/11299759/1053968)演示了它的用法。 – 2014-10-11 21:18:08