[Python-ideas] Break multiple loop levels
David Mertz
mertz at gnosis.cx
Sun May 12 13:26:10 EDT 2019
To be clear in this thread, I don't think I'm really ADVOCATING for a
multi-level break. My comments are simply noting that I personally fairly
often encounter the situation where they would be useful. At the same
time, I worry about Python gaining sometimes-useful features that
complicate the overall language and bring it closer to Perl's "everyone can
write in their own style."
So to answer Chris' question... well, i did find something recent, but it
has a ton of other extraneous stuff. But I've simplified to something that
isn't that much different from my example from my tablet yesterday, but is
fairly realistic still.
I have an existing function that looks roughly like this:
def find_needle_in_haystacks():
found_needle = False
for haystack in glob.glob('path/to/stuff/*'):
fh = open(fname)
header = fh.readline()
if get_format(header) == 'foo':
for line in fh:
status = process_foo(line)
if status = -1:
found_needle = True
break
elif get_format(header) == 'bar':
for line in fh:
status = process_bar(line)
if status = -1:
found_needle = True
break
if found_needle:
break
If I had a "labelled break" feature, I might rewrite it something like the
following (picking convenient syntax that I'm not per-se advocating as
best, even if the concept is adopted):
# Hypothetical future labelled break:
def find_needle_in_haystacks():
for haystack in glob.glob('path/to/stuff/*') label HAYSTACKS:
fh = open(fname)
header = fh.readline()
if get_format(header) == 'foo':
for line in fh:
if process_foo(line) == -1:
break HAYSTACKS
elif get_format(header) == 'bar':
for line in fh:
if process_bar(line) == -1:
break HAYSTACKS
In any case, it's often possible to either (a) redefine the inner loop
>> as some sort of container operation, or (b) redefine the outer
>> operation as a function, and use "return". So it would be helpful to
>> have an example that CAN'T be rewritten in one of those ways, to use
>> as a compelling example.
>>
>
--
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons. Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190512/edffd7f2/attachment-0001.html>
More information about the Python-ideas
mailing list