Syntactic structure for 'until <Exception>:' loop

Ian Kelly ian.g.kelly at gmail.com
Tue Jan 11 21:53:19 EST 2011


On 1/11/2011 7:22 PM, eblume wrote:
> This would be exactly equivalent to (but much more compact than):
>> while True:
> try:
> do_something()
> except Exception:
> break

Or perhaps:
try:
 while True:
 do_something()
except Exception:
 pass
> 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.

reader_iter = iter(self.reader)
headers = reader_iter.next()
# intermediate code
for line in reader_iter:
 data.append(line)
return data
Also note that recommended best practice is to wrap the "headers = 
reader_iter.next()" line in a try-except in case it raises a 
StopIteration. Otherwise it could get propagated silently up to some 
unrelated for loop higher in the stack, resulting in unexpected behavior.
Cheers,
Ian


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /