#!/usr/bin/env python from __future__ import with_statement from contextlib import contextmanager @contextmanager def lock(): yield class Good(list): def __iter__(self): it = list.__iter__(self) while True: try: with lock(): try: obj = it.next() except StopIteration: print "inner StopIteration" raise except StopIteration: print "outer StopIteration" raise yield obj class Bad(list): def __iter__(self): it = list.__iter__(self) while True: try: with lock(): #try: obj = it.next() #except StopIteration: #print "inner StopIteration" #raise except StopIteration: print "outer StopIteration" raise yield obj print list(Good(range(5))) print list(Bad(range(5))) # Never finishes