Why aren't colons optional?

Tim Peters tim.one at home.com
Sat Jan 19 22:43:03 EST 2002


[Edward K. Ream]
> Why are colons required after def, elif, else, except, finally, for, if,
> try and while?

It's not so arbitrary as that:  they're required when and only when a
statement introduces a block.  If you view this as a matter of memorizing
"which keywords need a colon", you're going at it wrong.

> One would think the colon would be optional when the colon is followed
> by a newline.

Python tries to encourage uniformity of coding style.  "Optional noise"
isn't Pythonic because of that.

> Obviously, colons are required in:
>
>   if a == 1 : b = c
>   elif a == 2 : b = d
>   else : b = e

That would be easy for a real parser even without colons.  The colons aren't
there for the benefit of parsers (modulo degenerate examples like "if a: (b,
c)" vs "if a (b, c)").  They're there primarily because studies with and
without colons in the ABC language (where Python got this idea) showed that
requiring colons helped people.  It turned out they're also extremely useful
for tools that *don't* have a full-blown parser behind them, like IDLE and
python-mode.el (any number of "toy parser" tools that do a shallow form of
parsing based on regexp tricks; if colons were made optional (they won't
be), you'd be amazed at how much would break).

> ...
>  My apologies if this is a perennial question.

It's regular but not frequent.  It seems that some peoples' brains just
aren't wired in such a way that the colons feel right to them, and so they
keep stumbling over them.  OTOH, I believe I've *never* forgotten the colon
over a decade of Python programming.  We're likely the extremes on that
scale.  Unluckily for you, it appears most people are on my side of the
midpoint, and most notably Guido <wink>.





More information about the Python-list mailing list