[Python-ideas] Loop labels
Nick Coghlan
ncoghlan at gmail.com
Sat Mar 10 03:47:19 CET 2012
On Sat, Mar 10, 2012 at 4:16 AM, Terry Reedy <tjreedy at udel.edu> wrote:
> Let us leave aside the fact that searching the matrix should normally be
> factored out as a function or method unto itself, separate from code that
> uses the found object.
No, let's *not* leave that out, because it gets to the heart of the
"attractive nuisance" aspect of labelled loop proposals.
The way this code should be written in Python:
# You should have a class Matrix. Python is not C.
# That class should offer a method to iterate over all the points
in the matrix
# Or, if it doesn't, you just write your own helper iterator
def iter_points(matrix):
for i in range(matrix.num_rows):
for j in range(matrix.num_columns):
yield i, j
# And now the problem devolves to a conventional Pythonic search loop
for i, j in iter_points(matrix):
item = matrix[i, j]
if item.is_interesting():
break
else:
raise RuntimeError("Nothing interesting found in {!r}".format(matrix))
# We use our interesting item here
Note that continue in the loop body also always applies to the
outermost loop because, from the compiler's point of view, there is
only *one* loop. The fact that there is a second loop internally is
hidden by the custom iterator.
So, whenever I hear "we should have labelled loops" I hear "I forgot I
could simply write a generator that produces the nested loop variables
as a tuple and hides any extra loops needed to create them from the
compiler". As Terry said:
"""Code in the example is the sort of spaghetti code that become
unreadable and unmaintainable with very many more states and input
conditions."""
Python offers higher level constructs for a reason. Changing the
language definition because people choose not to use them would be
foolish.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list