This code in this post is in Python 3, but aside from “cosmetic” differences,
such as next(g)
vs g.next()
it applies to Python 2 as well.
This is a companion discussion topic for the original entry at https://amir.rachum.com/blog/2017/03/03/generator-cleanup/