On Tue, 15 Nov 2005 21:54:07 -0500, Dan Sommers wrote: > On Wed, 16 Nov 2005 13:12:38 +1100, > Steven D'Aprano <[EMAIL PROTECTED]> wrote: > >> try: >> for item in obj: >> do_stuff(item) >> except TypeError, msg: >> if msg == "iteration over non-sequence": >> handle_non_iterator() >> else: >> # re-raise the exception >> raise > > But what it do_stuff tries to iterate over a non-sequence?
I can think of two solutions: (1) Write do_stuff carefully, and test it thoroughly on its own. If there are no bugs in do_stuff, you can be sure it isn't going to try to iterate over a non-iterator. This is a good argument for writing small, encapsulated, easily analysed and debugged pieces of code. (2) Muck about writing fragile, possibly buggy code: # untested try: for item in obj: flag = False try: do_stuff(item) except TypeError, msg: if msg == "iteration over non-sequence": flag = True # re-raise the exception raise except TypeError, msg: if flag: raise if msg == "iteration over non-sequence": handle_non_iterator() else: raise I think you can guess where my preference lies. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list