A use-case for for...else with no break
Steve D'Aprano
steve+python at pearwood.info
Fri Nov 3 05:30:34 EDT 2017
On Fri, 3 Nov 2017 04:22 pm, Paul Rubin wrote:
> Steve D'Aprano <steve+python at pearwood.info> writes:
>> for x in something():
>> print(x, end='')
>
> print(''.join(something()))
I hoped that people would recognise a simplified, toy example used only to
illustrate a technique, rather than an exact copy and paste of something I'm
actually doing.
Try this instead:
for s in sequence:
if isinstance(s, bytes):
try:
s = s.decode.('utf-8')
except UnicodeDecodeError:
s = s.decode.('latin-1')
print(s, end='')
else:
print()
Without writing a helper function, got a fancy one liner for that too?
Or another example, sometimes you really don't want to wait until the entire
sequence is processed before printing any output.
count = 0
for obj in sequence:
if count == 60:
print(' ', time.asctime())
count = 0
print('.', end='')
expensive_time_consuming_process_that_might_take_minutes_or_hours(obj)
count += 1
else:
del count
print()
print("finished at", time.asctime())
Now honestly, do you think the more complex examples illustrate the point I
was making, and the usefulness of for...else, better than the simple version?
Because I think they make them more complicated and hard to understand, and
distract from the point I am making.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list