generators and exceptions

Clark C. Evans cce at clarkevans.com
Mon Mar 17 02:30:56 EST 2003


On Sun, Mar 16, 2003 at 09:17:02AM +0100, Arne Koewing wrote:
| you may build your own object handling the iterator protocol, 
| that wraps up your generator:
| 
| from __future__ import generators
| 
| class MyExc(Exception): pass
| 
| def mygen(val):
|     while val >= 0:
|         if val % 2:
|             yield MyExc()  #yield it don't raise
|         else:
|             yield val
|         val = val - 1
|                 
| 
| class handler:
|     def __init__(self,itr):
|         self.iterator=itr
|     def __getitem__(self,index):
|         val=self.iterator.next()
|         if isinstance(val,Exception):
|             raise val
|         return val
| 
| iterator = iter(handler(mygen(4)))
| while 1:
|     try:
|         val = iterator.next()
|         print val
|     except MyExc: print 'catched'
|     except StopIteration: break

Thanks.   This is very close to what I implemented (so that
I could use generators).  However, it is, one must admit,
not as clear as if generators could raise exceptions and
recover from them.

Clark





More information about the Python-list mailing list