[Python-ideas] for/else syntax
steve at pearwood.info
Sat Oct 3 08:39:47 CEST 2009
On Sat, 3 Oct 2009 03:08:49 pm Nick Coghlan wrote:
> [...] we should at least investigate
> having the compiler itself raise at least a SyntaxWarning if it
> encounters a for/else or while/else construct without also
> encountering a break statement inside the loop.
> For a loop with no break statements the else clause will *always* be
Modulo returns and exceptions.
> hence using the clause is completely redundant
True. But there is an effectively infinite amount of completely
redundant code possible in Python. The performance hit and maintenance
burden of raising warnings for redundant code would be immense, to say
nothing of the nuisance value for the developer.
Such warnings don't belong in the language, they belong in PyLint or
> - the code
> it contains might as well be dedented and placed inline at the same
> level as the loop header.
True, except that the else clause clearly flags it as part of the
semantic unit together with the for loop. Dedenting the code flags it
as separate from the for loop.
Apart from free style comments, we don't have a way of flagging code
blobs finer than the function -- Python doesn't work that way. For
instance, we're reduced to marking logical groups of code smaller than
a function with comments.
# Initialise the values.
x = 2
y = 3 + x
z = x*y + 1
# Process the sequence.
value = 0
for o in seq:
value = o - value + z
value = 1.0/value
# Do something else with it.
value = parrot(value)
It would be interesting to hypothesise about languages that naturally
grouped (e.g.) the for loop and its pre-entry and post-exit code
together into one obvious code unit. Python isn't that language, but
(by accident, I'm sure) the else clause comes close.
More information about the Python-ideas