April 1, 2005 — originally posted on artima.com
Python currently gives you a lot of freedom on how to format your code. For example, instead of this:
def fool(one, four):
year = 2005
while year < 10000000:
year *= 10
return year + four*100 + one
you could just as well have written this:
def fool ( one , four ) :
year=2005
while( year< 10000000 ):
year*= 10
return ( year+four * 100+one )
This is a clear violation of TOOWTDI and enables poorly written code.
Therefore, I propose that as soon as practical, Python should enforce the following rules for horizontal whitespace:
- All code indented with four spaces. This will also get rid of the tabs problem!
- No redundant parentheses allowed (e.g. no "return(1)" where "return 1" would do).
- No whitespace immediately following a left parentheses or immediately before a right parenthesis.
- No whitespace before a left parenthesis that starts an argument list, or before a left square bracket that starts an index expression (e.g. "x[y]").
- No whitespace before a comma or semicolon.
- Exactly one space required after a comma or semicolon (except when at the end of a line).
- No semicolon at the end of a line (it's redundant).
- More than one consecutive space within an expression is never allowed.
- Asignment and comparison operators must be surrounded by spaces.
- The amount of whitespace on both sides of a binary operator should be the same.
- If variable amounts of whitespace are used within an expression, this should correspond to the relative priorities of the operators used. For example: "1*2 + 3*4" is okay but "1*2 + 3 * 4" is not. However, "1*2+3*4" is still encouraged.
- No space allowed before a colon.
- In a dictionary display, exactly one space required after a colon. In a slice, none.
- The short form of a block ("if x: y") is abandoned; you must use the newline-plus-indentation form.
A limited form of vertical whitespace fascism may also be introduced, although this may encounter more resistance, so it may be put off until Python 3.0:
- At least one blank line should separate function or method definitions.
- At least two blank lines should separate classes.
In order to give users sufficient time to adapt their coding style, the new syntax will be optional in Python 2.5, and required in Python 2.6. In Python 2.5, you can enable the strict whitespace checking for a particular module with a future statement:
from __future__ import whitespace
I have hacked up a quick and dirty implementation, which is available at the following SourceForge URL (new, now updated!): http://sourceforge.net/tracker/index.php?func=detail&aid=1175070&group_id=5470&atid=305470
Feedback, as always, is welcome!