Entry
Are colons unnecessary in my Python code?
May 16th, 2000 07:35
unknown unknown, Courageous, David Porter, François Pinard, Moshe Zadka, Dirck Blaskey
Lead in discussion:
Sometimes colons seem syntactically unnecessary. For example:
if <condition>:
statement
else:
statement
Really, else doesn't need a colon, as far as I can tell (I can see the
need for the if, supposing you want to have the statement on the same
line).
Answer(s):
- When using python-mode in Emacs (or jed), the colon facilitates
auto-indention. Also, if you forget the colon, the next line will not be
indented, so you will catch your mistake.
- Granted, but it is always good for a language to have a bit of
redundant information. When properly thought, such redundancy prevents
various mistakes from programmers (once they are used to it, of course
:-), and often increase overall legibility.
- Theoretically, a colon is only necessary in things like
if yes: print "yes"
Since otherwise the parser can figure out when to stick a colon.
However, usability studies show people are more comfortable when the
beginning of a block is signaled, and I can see why:
if yes
print "yes"
Seems....naked. Much less readable then
if yes:
print "yes"
Guido didn't want 10 ways (or even 2) to spell things, so the colon is
mandated for all.
- > if yes: print "yes"
Oddly enough, the parser doesn't really need the colon here either.
It can manage to figure out where the if expression ends without it.
The colon is almost entirely for readability purposes.
(there are a couple of places where ambiguity occurs without it).
If you're curious about the other thread,
or about Python without colons,
or to test my above assertion,
check out:
http://www.danbala.com/python/colopt