diff --git a/pep-0008.txt b/pep-0008.txt index ca3887739..380d89645 100644 --- a/pep-0008.txt +++ b/pep-0008.txt @@ -81,9 +81,9 @@ using Python's implicit line joining inside parentheses, brackets and braces, or using a *hanging indent* [#fn-hi]_. When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to -clearly distinguish itself as a continuation line. +clearly distinguish itself as a continuation line:: -Yes:: + # Correct: # Aligned with opening delimiter. foo = long_function_name(var_one, var_two, @@ -100,7 +100,9 @@ Yes:: var_one, var_two, var_three, var_four) -No:: +:: + + # Wrong: # Arguments on first line forbidden when not using vertical alignment. foo = long_function_name(var_one, var_two, @@ -256,7 +258,8 @@ moved away from its operand and onto the previous line. Here, the eye has to do extra work to tell which items are added and which are subtracted:: - # No: operators sit far away from their operands + # Wrong: + # operators sit far away from their operands income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - @@ -272,7 +275,8 @@ displayed formulas always break before binary operations" [3]_. Following the tradition from mathematics usually results in more readable code:: - # Yes: easy to match operators with operands + # Correct: + # easy to match operators with operands income = (gross_wages + taxable_interest + (dividends - qualified_dividends) @@ -338,13 +342,19 @@ Imports - Imports should usually be on separate lines:: - Yes: import os - import sys + # Correct: + import os + import sys + + :: + + # Wrong: + import sys, os - No: import sys, os It's okay to say this though:: + # Correct: from subprocess import Popen, PIPE - Imports are always put at the top of the file, just after any module @@ -451,37 +461,52 @@ Pet Peeves Avoid extraneous whitespace in the following situations: -- Immediately inside parentheses, brackets or braces. :: +- Immediately inside parentheses, brackets or braces:: - Yes: spam(ham[1], {eggs: 2}) - No: spam( ham[ 1 ], { eggs: 2 } ) + # Correct: + spam(ham[1], {eggs: 2}) -- Between a trailing comma and a following close parenthesis. :: + :: - Yes: foo = (0,) - No: bar = (0, ) + # Wrong: + spam( ham[ 1 ], { eggs: 2 } ) + +- Between a trailing comma and a following close parenthesis:: + + # Correct: + foo = (0,) + + :: + + # Wrong: + bar = (0, ) - Immediately before a comma, semicolon, or colon:: - Yes: if x == 4: print x, y; x, y = y, x - No: if x == 4 : print x , y ; x , y = y , x + # Correct: + if x == 4: print x, y; x, y = y, x + + :: + + # Wrong: + if x == 4 : print x , y ; x , y = y , x - However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). In an extended slice, both colons must have the same amount of spacing applied. Exception: - when a slice parameter is omitted, the space is omitted. - - Yes:: + when a slice parameter is omitted, the space is omitted:: + # Correct: ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:] ham[lower:upper], ham[lower:upper:], ham[lower::step] ham[lower+offset : upper+offset] ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)] ham[lower + offset : upper + offset] - No:: + :: + # Wrong: ham[lower + offset:upper + offset] ham[1: 9], ham[1 :9], ham[1:9 :3] ham[lower : : upper] @@ -490,26 +515,36 @@ Avoid extraneous whitespace in the following situations: - Immediately before the open parenthesis that starts the argument list of a function call:: - Yes: spam(1) - No: spam (1) + # Correct: + spam(1) + + :: + + # Wrong: + spam (1) - Immediately before the open parenthesis that starts an indexing or slicing:: - Yes: dct['key'] = lst[index] - No: dct ['key'] = lst [index] + # Correct: + dct['key'] = lst[index] + + :: + + # Wrong: + dct ['key'] = lst [index] - More than one space around an assignment (or other) operator to - align it with another. - - Yes:: + align it with another:: + # Correct: x = 1 y = 2 long_variable = 3 - No:: + :: + # Wrong: x = 1 y = 2 long_variable = 3 @@ -533,18 +568,18 @@ Other Recommendations whitespace around the operators with the lowest priority(ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary - operator. - - Yes:: + operator:: + # Correct: i = i + 1 submitted += 1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b) - No:: + :: + # Wrong: i=i+1 submitted +=1 x = x * 2 - 1 @@ -553,51 +588,50 @@ Other Recommendations - Function annotations should use the normal rules for colons and always have spaces around the ``->`` arrow if present. (See - `Function Annotations`_ below for more about function annotations.) - - Yes:: + `Function Annotations`_ below for more about function annotations.):: + # Correct: def munge(input: AnyStr): ... def munge() -> PosInt: ... - No:: + :: + # Wrong: def munge(input:AnyStr): ... def munge()->PosInt: ... - Don't use spaces around the ``=`` sign when used to indicate a keyword argument, or when used to indicate a default value for an - *unannotated* function parameter. - - Yes:: + *unannotated* function parameter:: + # Correct: def complex(real, imag=0.0): return magic(r=real, i=imag) - No:: + :: + # Wrong: def complex(real, imag = 0.0): return magic(r = real, i = imag) When combining an argument annotation with a default value, however, do use - spaces around the ``=`` sign: - - Yes:: + spaces around the ``=`` sign:: + # Correct: def munge(sep: AnyStr = None): ... def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ... - No:: + :: + # Wrong: def munge(input: AnyStr=None): ... def munge(input: AnyStr, limit = 1000): ... - Compound statements (multiple statements on the same line) are - generally discouraged. - - Yes:: + generally discouraged:: + # Correct: if foo == 'blah': do_blah_thing() do_one() @@ -606,6 +640,7 @@ Other Recommendations Rather not:: + # Wrong: if foo == 'blah': do_blah_thing() do_one(); do_two(); do_three() @@ -615,12 +650,14 @@ Other Recommendations Rather not:: + # Wrong: if foo == 'blah': do_blah_thing() for x in lst: total += x while t < 10: t = delay() Definitely not:: + # Wrong: if foo == 'blah': do_blah_thing() else: do_non_blah_thing() @@ -639,14 +676,14 @@ When to Use Trailing Commas Trailing commas are usually optional, except they are mandatory when making a tuple of one element (and in Python 2 they have semantics for the ``print`` statement). For clarity, it is recommended to surround -the latter in (technically redundant) parentheses. - -Yes:: +the latter in (technically redundant) parentheses:: + # Correct: FILES = ('setup.cfg',) -OK, but confusing:: +:: + # Wrong: FILES = 'setup.cfg', When trailing commas are redundant, they are often helpful when a @@ -656,10 +693,9 @@ to put each value (etc.) on a line by itself, always adding a trailing comma, and add the close parenthesis/bracket/brace on the next line. However it does not make sense to have a trailing comma on the same line as the closing delimiter (except in the above case of singleton -tuples). - -Yes:: +tuples):: + # Correct: FILES = [ 'setup.cfg', 'tox.ini', @@ -668,8 +704,9 @@ Yes:: error=True, ) -No:: +:: + # Wrong: FILES = ['setup.cfg', 'tox.ini',] initialize(FILES, error=True,) @@ -1089,14 +1126,14 @@ Programming Recommendations - Use ``is not`` operator rather than ``not ... is``. While both expressions are functionally identical, the former is more readable - and preferred. - - Yes:: + and preferred:: + # Correct: if foo is not None: - No:: + :: + # Wrong: if not foo is None: - When implementing ordering operations with rich comparisons, it is @@ -1116,14 +1153,14 @@ Programming Recommendations that confusion doesn't arise in other contexts. - Always use a def statement instead of an assignment statement that binds - a lambda expression directly to an identifier. - - Yes:: + a lambda expression directly to an identifier:: + # Correct: def f(x): return 2*x - No:: + :: + # Wrong: f = lambda x: 2*x The first form means that the name of the resulting function object is @@ -1212,10 +1249,9 @@ Programming Recommendations - Additionally, for all try/except clauses, limit the ``try`` clause to the absolute minimum amount of code necessary. Again, this - avoids masking bugs. - - Yes:: + avoids masking bugs:: + # Correct: try: value = collection[key] except KeyError: @@ -1223,8 +1259,9 @@ Programming Recommendations else: return handle_value(value) - No:: + :: + # Wrong: try: # Too broad! return handle_value(collection[key]) @@ -1237,15 +1274,15 @@ Programming Recommendations after use. A try/finally statement is also acceptable. - Context managers should be invoked through separate functions or methods - whenever they do something other than acquire and release resources. - - Yes:: + whenever they do something other than acquire and release resources:: + # Correct: with conn.begin_transaction(): do_stuff_in_transaction(conn) - No:: + :: + # Wrong: with conn: do_stuff_in_transaction(conn) @@ -1259,9 +1296,9 @@ Programming Recommendations any return statement returns an expression, any return statements where no value is returned should explicitly state this as ``return None``, and an explicit return statement should be present at the - end of the function (if reachable). + end of the function (if reachable):: - Yes:: + # Correct: def foo(x): if x >= 0: @@ -1274,7 +1311,9 @@ Programming Recommendations return None return math.sqrt(x) - No:: + :: + + # Wrong: def foo(x): if x >= 0: @@ -1296,53 +1335,74 @@ Programming Recommendations startswith() and endswith() are cleaner and less error prone:: - Yes: if foo.startswith('bar'): - No: if foo[:3] == 'bar': + # Correct: + if foo.startswith('bar'): + + :: + + # Wrong: + if foo[:3] == 'bar': - Object type comparisons should always use isinstance() instead of - comparing types directly. :: + comparing types directly:: - Yes: if isinstance(obj, int): + # Correct: + if isinstance(obj, int): - No: if type(obj) is type(1): + :: - When checking if an object is a string, keep in mind that it might - be a unicode string too! In Python 2, str and unicode have a - common base class, basestring, so you can do:: + # Wrong: + if type(obj) is type(1): + +When checking if an object is a string, keep in mind that it might +be a unicode string too! In Python 2, str and unicode have a +common base class, basestring, so you can do:: if isinstance(obj, basestring): - Note that in Python 3, ``unicode`` and ``basestring`` no longer exist - (there is only ``str``) and a bytes object is no longer a kind of - string (it is a sequence of integers instead). +Note that in Python 3, ``unicode`` and ``basestring`` no longer exist +(there is only ``str``) and a bytes object is no longer a kind of +string (it is a sequence of integers instead). - For sequences, (strings, lists, tuples), use the fact that empty - sequences are false. :: + sequences are false:: - Yes: if not seq: - if seq: + # Correct: + if not seq: + if seq: - No: if len(seq): - if not len(seq): + :: + + # Wrong: + if len(seq): + if not len(seq): - Don't write string literals that rely on significant trailing whitespace. Such trailing whitespace is visually indistinguishable and some editors (or more recently, reindent.py) will trim them. -- Don't compare boolean values to True or False using ``==``. :: +- Don't compare boolean values to True or False using ``==``:: - Yes: if greeting: - No: if greeting == True: - Worse: if greeting is True: + # Correct: + if greeting: + + :: + + # Wrong: + if greeting == True: + + Worse:: + + # Wrong: + if greeting is True: - Use of the flow control statements ``return``/``break``/``continue`` within the finally suite of a ``try...finally``, where the flow control statement would jump outside the finally suite, is discouraged. This is because such statements will implicitly cancel any active exception - that is propagating through the finally suite. - - No:: + that is propagating through the finally suite:: + # Wrong: def foo(): try: 1 / 0 @@ -1409,9 +1469,9 @@ similar to those on function annotations described above: - There should be no space before the colon. - If an assignment has a right hand side, then the equality sign should have - exactly one space on both sides. + exactly one space on both sides:: -- Yes:: + # Correct: code: int @@ -1419,7 +1479,9 @@ similar to those on function annotations described above: coords: Tuple[int, int] label: str = '' -- No:: + :: + + # Wrong: code:int # No space after colon code : int # Space before colon