Why not allow empty code blocks?
Steven D'Aprano
steve at pearwood.info
Sat Jul 23 11:55:29 EDT 2016
On Sun, 24 Jul 2016 12:06 am, BartC wrote:
> pass can only do so much. If doesn't help here:
>
> for x in sequence:
> print("Something")
> print("Something else")
>
> Was the second print meant to be indented as well or not?
True. But once you start wondering about code the programmer *hasn't*
written, you could drive yourself crazy:
...but what if the second print is supposed to follow
an "if" clause, which has been left out...?
*Most* for-loops have non-empty blocks. Only a tiny minority have empty
blocks for any appreciable period of time. (This is not 1970, and we don't
write timing loops like "for x in range(1000): pass".)
*Most* code is correctly indented. So the interpreter should assume that
indentation *is correct*, unless there is a reason to doubt that. What sort
of reasons could there be?
- if the indentation increases when it shouldn't:
print("Hello")
print("World!") # unexpected indent
- if it dedents to a value that doesn't align with a previous block:
for x in sequence:
print(x)
print("dedented") # half-way between current and previous block
- if it doesn't indent when you expect it to:
for x in sequence:
print(x)
Yes, that last one *could* be an empty block. But empty blocks are rare. Its
more likely to be an error. If it's not an error, than the programmer can
just insert a "pass" statement to satisfy the interpreter.
> Perhaps rather than 'pass', the language ought to have provided an
> optional 'end' keyword to mark the end of a block. Then there would be
> less speculation about what was meant:
It can't be optional. If it were optional, we'd be no better off:
for x in sequence:
print(x)
The "end" is missing, but is it missing from the end of the empty block, or
the end of the non-empty block?
for x in sequence:
end
print(x)
for x in sequence:
print(x)
end
In any case, using "end" instead of "pass" is a poor tradeoff. Instead of
needing to use "pass" (say) one time in a thousand when it is needed, you
would need to use "end" 999 times in a thousand when it *isn't* needed.
> for x in sequence:
> print("Something")
> end
> print("Something else")
>
> (And no speculation at all if 'end' was mandatory. Python already
> provides 'else' (and 'except'?) which can do a similar job in some
> circumstances.)
--
Steven
“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