Situation | Recommended Way | Not Recommended |
Immediately inside parentheses, brackets or braces. | spam(ham[1], {eggs: 2}) | spam( ham[ 1 ], { eggs: 2 } ) |
Immediately before a comma, semicolon, or colon. | if x == 4: print x, y; x, y = y, x | if x == 4 : print x , y ; x , y = y , x |
Immediately before the open parenthesis that starts the argument list of a function call. | spam(1) | spam (1) |
Immediately before the open parenthesis that starts an indexing or slicing | dict['key'] = list[index] | dict ['key'] = list [index] |
More than one space around an assignment (or other) operator to align it with another |
x = 1
long_variable = 3 |
x = 1
long_variable = 3 |
Always surround these binary operators with a single space on either side: assignment ( ), augmented assignment (+ , -= etc.), comparisons ( =, <, >, , <>, <=, >=, in, not in, is, is not), Booleans (and, or, not)</pre> |
i = i + 1
submitted += 1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b) |
i=i+1
submitted +=1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b) |
Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value. |
def complex(real, imag=0.0):
return magic(r=real, i=imag) |
def complex(real, imag = 0.0):
return magic(r = real, i = imag) |
Compound statements (multiple statements on the same line) are generally discouraged. |
if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three() |
if foo == 'blah': do_blah_thing() do_one();
do_two(); do_three() |
While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines! | - | if foo == 'blah': do_blah_thing()
else: do_non_blah_thing()
try: something()
finally: cleanup()
do_one(); do_two(); do_three(long, argument,
list, like, this)
if foo == 'blah': one(); two(); three() |