Syntactic structure for 'until <Exception>:' loop

eblume blume.erich at gmail.com
Tue Jan 11 21:22:33 EST 2011


I'm still quite new to Python and I'm probably going about this
entirely the wrong way, but it recently struck me that there might be
the need for a control flow loop based on exception handling. First
let me give the proposed syntax:

until <Exception[, Exception]...>:
    do_something()

This would be exactly equivalent to (but much more compact than):

while True:
    try:
        do_something()
    except Exception:
        break

Now, why would anyone want this structure? In my case, I'm using it
(well, the latter form of it, obviously) to loop over an iterator
object that was not created via the 'for obj in collection:' syntax.
Here's the actual code snippet:

                headers = self.reader.next()
                ... intermediate code ....
                while True:
                        try:
                                line = self.reader.next()
                        except StopIteration:
                                return data
                        data.append(line)

I'm sure I'm doing this in a very backward and wrong way, and would
appreciate tips on a better way to accomplish the same task. Obviously
there is an existing syntax which handles the same situations, and I
don't suspect that this will be an embraced proposal, I'm more hoping
to spark some conversation.

Thanks!



More information about the Python-list mailing list