PyIter_Next returns NULL to indicate either that an error occurred or that there are no further values to return. To check for errors, C extensions are required to call PyErr_Occurred() when exiting the iteration loop. See the documentation here:
https://docs.python.org/2/c-api/iter.html#c.PyIter_Next
We do this everywhere in PyMongo's C extensions except in the write_dict function on _cbsonmodule.c. This appears to be a very old bug, dating all the way back to the initial C extensions implementation in 2009.
It's not clear to me what impact, if any, this bug actually has, as write_dict seems to always be called inside of another loop that does call PyErr_Occurred on exit. We should fix it anyway.