Check Python source code formatting, according to PEP 8.
For usage and a list of options, try this: $ python pycodestyle.py -h
This program and its regression test suite live here: https://github.com/pycqa/pycodestyle
Groups of errors and warnings: E errors W warnings 100 indentation 200 whitespace 300 blank lines 400 imports 500 line length 600 deprecation 700 statements 900 syntax error
Class |
|
Collect the results of the checks. |
Class |
|
Load a Python source file, tokenize it, check coding style. |
Class |
|
Collect and print the results for the changed lines only. |
Class |
|
Collect the results of the checks and print the filenames. |
Class |
|
Collect and print the results of the checks. |
Class |
|
Initialize a PEP-8 instance with few options. |
Function | ambiguous |
Never use the characters 'l', 'O', or 'I' as variable names. |
Function | bare |
When catching exceptions, mention specific exceptions when possible. |
Function | blank |
Separate top-level function and class definitions with two blank lines. |
Function | break |
Avoid breaks after binary operators. |
Function | break |
Avoid breaks before binary operators. |
Function | comparison |
Negative comparison should be done using "not in" and "is not". |
Function | comparison |
Comparison to singletons should use "is" or "is not". |
Function | comparison |
Object type comparisons should always use isinstance(). |
Function | compound |
Compound statements (on the same line) are generally discouraged. |
Function | continued |
Continuation lines indentation. |
Function | expand |
Return the amount of indentation. |
Function | explicit |
Avoid explicit line join between brackets. |
Function | extraneous |
Avoid extraneous whitespace. |
Function | filename |
Check if patterns contains a pattern that matches filename. |
Function | get |
Create the parser for the program. |
Function | imports |
Place imports on separate lines. |
Function | indentation |
Use 4 spaces per indentation level. |
Function | maximum |
Limit all doc lines to a maximum of 72 characters. |
Function | maximum |
Limit all lines to a maximum of 79 characters. |
Function | missing |
Each comma, semicolon or colon should be followed by whitespace. |
Function | missing |
Multiple imports in form from x import (a, b, c) should have space between import statement and parenthesised name list. |
Function | missing |
Surround operators with a single space on either side. |
Function | module |
Place imports at the top of the file. |
Function | mute |
Replace contents with 'xxx' to prevent syntax matching. |
Function | normalize |
Parse a comma-separated list of paths. |
Function | parse |
Return a dictionary of matching lines. |
Function | process |
Process options passed either via arglist or command line args. |
Function | python |
'async' and 'await' are reserved keywords starting at Python 3.7. |
Function | python |
Use repr() instead of backticks in Python 3. |
Function | python |
The {}.has_key() method is removed in Python 3: use the 'in' operator. |
Function | python |
Invalid escape sequences are deprecated in Python 3.6. |
Function | python |
New code should always use != instead of <>. |
Function | python |
When raising an exception, use "raise ValueError('message')". |
Function | read |
Read and parse configurations. |
Function | readlines |
Read the source code. |
Function | register |
Register a new check object. |
Function | tabs |
On new projects, spaces-only are strongly recommended over tabs. |
Function | tabs |
Never mix tabs and spaces. |
Function | trailing |
Trailing blank lines are superfluous. |
Function | trailing |
Trailing whitespace is superfluous. |
Function | update |
Adds one to the counts of each appearance of characters in s, for characters in counts |
Function | whitespace |
Avoid extraneous whitespace after a comma or a colon. |
Function | whitespace |
Avoid extraneous whitespace around keywords. |
Function | whitespace |
Don't use spaces around the '=' sign in function arguments. |
Function | whitespace |
Avoid extraneous whitespace around an operator. |
Function | whitespace |
Separate inline comments by at least two spaces. |
Function | whitespace |
Avoid extraneous whitespace. |
Constant | ARITHMETIC |
Undocumented |
Constant | ASSIGNMENT |
Undocumented |
Constant | BENCHMARK |
Undocumented |
Constant | BLANK |
Undocumented |
Constant | COMPARE |
Undocumented |
Constant | COMPARE |
Undocumented |
Constant | COMPARE |
Undocumented |
Constant | DEFAULT |
Undocumented |
Constant | DEFAULT |
Undocumented |
Constant | DOCSTRING |
Undocumented |
Constant | DUNDER |
Undocumented |
Constant | ERRORCODE |
Undocumented |
Constant | EXTRANEOUS |
Undocumented |
Constant | FUNCTION |
Undocumented |
Constant | HUNK |
Undocumented |
Constant | INDENT |
Undocumented |
Constant | KEYWORD |
Undocumented |
Constant | KEYWORDS |
Undocumented |
Constant | LAMBDA |
Undocumented |
Constant | MAX |
Undocumented |
Constant | MAX |
Undocumented |
Constant | NEWLINE |
Undocumented |
Constant | OPERATOR |
Undocumented |
Constant | PROJECT |
Undocumented |
Constant | RAISE |
Undocumented |
Constant | REPORT |
Undocumented |
Constant | RERAISE |
Undocumented |
Constant | SINGLETONS |
Undocumented |
Constant | SKIP |
Undocumented |
Constant | SKIP |
Undocumented |
Constant | STARTSWITH |
Undocumented |
Constant | STARTSWITH |
Undocumented |
Constant | STARTSWITH |
Undocumented |
Constant | TESTSUITE |
Undocumented |
Constant | UNARY |
Undocumented |
Constant | WHITESPACE |
Undocumented |
Constant | WHITESPACE |
Undocumented |
Constant | WS |
Undocumented |
Constant | WS |
Undocumented |
Variable | __version__ |
Undocumented |
Variable | isidentifier |
Undocumented |
Variable | noqa |
Undocumented |
Variable |
|
Undocumented |
Variable | USER |
Undocumented |
Function | _break |
Private function to reduce duplication. |
Function | _get |
Undocumented |
Function | _is |
Undocumented |
Function | _is |
Undocumented |
Function | _main |
Parse options and run checks on Python source. |
Function | _parse |
Split and strip and discard empties. |
Constant | _SYMBOLIC |
Undocumented |
Variable | _checks |
Undocumented |
Never use the characters 'l', 'O', or 'I' as variable names.
In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead.
Okay: L = 0 Okay: o = 123 Okay: i = 42 E741: l = 0 E741: O = 123 E741: I = 42
Variables can be bound in several other contexts, including class and function definitions, 'global' and 'nonlocal' statements, exception handlers, and 'with' and 'for' statements. In addition, we have a special handling for function parameters.
Okay: except AttributeError as o: Okay: with lock as L: Okay: foo(l=12) Okay: for a in foo(l=12): E741: except AttributeError as O: E741: with lock as l: E741: global I E741: nonlocal l E741: def foo(l): E741: def foo(l=12): E741: l = foo(l=12) E741: for l in range(10): E742: class I(object): E743: def l(x):
When catching exceptions, mention specific exceptions when possible.
Okay: except Exception: Okay: except BaseException: E722: except:
def blank_lines(logical_line, blank_lines, indent_level, line_number, blank_before, previous_logical, previous_unindented_logical_line, previous_indent_level, lines): ¶
Separate top-level function and class definitions with two blank lines.
Method definitions inside a class are separated by a single blank line.
Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
Okay: def a():n passnnndef b():n pass Okay: def a():n passnnnasync def b():n pass Okay: def a():n passnnn# Foon# Barnndef b():n pass Okay: default = 1nfoo = 1 Okay: classify = 1nfoo = 1
E301: class Foo:n b = 0n def bar():n pass E302: def a():n passnndef b(n):n pass E302: def a():n passnnasync def b(n):n pass E303: def a():n passnnnndef b(n):n pass E303: def a():nnnn pass E304: @decoratornndef a():n pass E305: def a():n passna() E306: def a():n def b():n passn def c():n pass
Avoid breaks after binary operators.
The preferred place to break around a binary operator is before the operator, not after it.
W504: (width == 0 +n height == 0) W504: (width == 0 andn height == 0) W504: var = (1 &n ~2)
Okay: foo(n -x) Okay: foo(xn []) Okay: x = '''n''' + '' Okay: x = '' + '''n''' Okay: foo(x,n -y) Okay: foo(x, # commentn -y)
The following should be W504 but unary_context is tricky with these Okay: var = (1 /n -2) Okay: var = (1 +n -1 +n -2)
Avoid breaks before binary operators.
The preferred place to break around a binary operator is after the operator, not before it.
W503: (width == 0n + height == 0) W503: (width == 0n and height == 0) W503: var = (1n & ~2) W503: var = (1n / -2) W503: var = (1n + -1n + -2)
Okay: foo(n -x) Okay: foo(xn []) Okay: x = '''n''' + '' Okay: foo(x,n -y) Okay: foo(x, # commentn -y)
Negative comparison should be done using "not in" and "is not".
Okay: if x not in y:n pass Okay: assert (X in Y or X is Z) Okay: if not (X in Y):n pass Okay: zz = x is not y E713: Z = not X in Y E713: if not X.B in Y:n pass E714: if not X is Y:n pass E714: Z = not X.B is Y
Comparison to singletons should use "is" or "is not".
Comparisons to singletons like None should always be done with "is" or "is not", never the equality operators.
Okay: if arg is not None: E711: if arg != None: E711: if None == arg: E712: if arg == True: E712: if False == arg:
Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!
Object type comparisons should always use isinstance().
Do not compare types directly.
Okay: if isinstance(obj, int): E721: 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.3, str and unicode have a common base class, basestring, so you can do:
Okay: if isinstance(obj, basestring): Okay: if type(a1) is type(b1):
Compound statements (on the same line) are generally discouraged.
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!
Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name.
Okay: if foo == 'blah':n do_blah_thing() Okay: do_one() Okay: do_two() Okay: do_three()
E701: if foo == 'blah': do_blah_thing() E701: for x in lst: total += x E701: while t < 10: t = delay() E701: if foo == 'blah': do_blah_thing() E701: else: do_non_blah_thing() E701: try: something() E701: finally: cleanup() E701: if foo == 'blah': one(); two(); three() E702: do_one(); do_two(); do_three() E703: do_four(); # useless semicolon E704: def f(x): return 2*x E731: f = lambda x: 2*x
def continued_indentation(logical_line, tokens, indent_level, hang_closing, indent_char, noqa, verbose): ¶
Continuation lines indentation.
Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent.
When using a hanging indent these considerations should be applied: - there should be no arguments on the first line, and - further indentation should be used to clearly distinguish itself
as a continuation line.
Okay: a = (n) E123: a = (n )
Okay: a = (n 42) E121: a = (n 42) E122: a = (n42) E123: a = (n 42n ) E124: a = (24,n 42n) E125: if (n b):n pass E126: a = (n 42) E127: a = (24,n 42) E128: a = (24,n 42) E129: if (a orn b):n pass E131: a = (n 42n 24)
Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ') 4 >>> expand_indent('\t') 8 >>> expand_indent(' \t') 8 >>> expand_indent(' \t') 16
Avoid explicit line join between brackets.
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
E502: aaa = [123, \n 123] E502: aaa = ("bbb " \n "ccc")
Okay: aaa = [123,n 123] Okay: aaa = ("bbb "n "ccc") Okay: aaa = "bbb " \n "ccc" Okay: aaa = 123 # \
Avoid extraneous whitespace.
Avoid extraneous whitespace in these situations: - Immediately inside parentheses, brackets or braces. - Immediately before a comma, semicolon, or colon.
Okay: spam(ham[1], {eggs: 2}) E201: spam( ham[1], {eggs: 2}) E201: spam(ham[ 1], {eggs: 2}) E201: spam(ham[1], { eggs: 2}) E202: spam(ham[1], {eggs: 2} ) E202: spam(ham[1 ], {eggs: 2}) E202: spam(ham[1], {eggs: 2 })
E203: if x == 4: print x, y; x, y = y , x E203: if x == 4: print x, y ; x, y = y, x E203: if x == 4 : print x, y; x, y = y, x
Check if patterns contains a pattern that matches filename.
If patterns is unspecified, this always returns True.
Place imports on separate lines.
Okay: import osnimport sys E401: import sys, os
Okay: from subprocess import Popen, PIPE Okay: from myclas import MyClass Okay: from foo.bar.yourclass import YourClass Okay: import myclass Okay: import foo.bar.yourclass
def indentation(logical_line, previous_logical, indent_char, indent_level, previous_indent_level): ¶
Use 4 spaces per indentation level.
For really old code that you don't want to mess up, you can continue to use 8-space tabs.
Okay: a = 1 Okay: if a == 0:n a = 1 E111: a = 1 E114: # a = 1
Okay: for item in items:n pass E112: for item in items:npass E115: for item in items:n# Hin pass
Okay: a = 1nb = 2 E113: a = 1n b = 2 E116: a = 1n # b = 2
Limit all doc lines to a maximum of 72 characters.
For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended.
Reports warning W505
def maximum_line_length(physical_line, max_line_length, multiline, line_number, noqa): ¶
Limit all lines to a maximum of 79 characters.
There are still many devices around that are limited to 80 character lines; plus, limiting windows to 80 characters makes it possible to have several windows side-by-side. The default wrapping on such devices looks ugly. Therefore, please limit all lines to a maximum of 79 characters. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended.
Reports error E501.
Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b] Okay: (3,) Okay: a[1:4] Okay: a[:4] Okay: a[1:] Okay: a[1:4:2] E231: ['a','b'] E231: foo(bar,baz) E231: [{'a':'b'}]
Multiple imports in form from x import (a, b, c) should have space between import statement and parenthesised name list.
Okay: from foo import (bar, baz) E275: from foo import(bar, baz) E275: from importable.module import(bar, baz)
Surround operators with a single space on either side.
- 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).
- If operators with different priorities are used, consider adding whitespace around the operators with the lowest priorities.
Okay: i = i + 1 Okay: submitted += 1 Okay: x = x * 2 - 1 Okay: hypot2 = x * x + y * y Okay: c = (a + b) * (a - b) Okay: foo(bar, key='word', *args, **kwargs) Okay: alpha[:-i]
E225: i=i+1 E225: submitted +=1 E225: x = x /2 - 1 E225: z = x **y E225: z = 1and 1 E226: c = (a+b) * (a-b) E226: hypot2 = x*x + y*y E227: c = a|b E228: msg = fmt%(errno, errmsg)
def module_imports_on_top_of_file(logical_line, indent_level, checker_state, noqa): ¶
Place imports at the top of the file.
Always put imports at the top of the file, just after any module comments and docstrings, and before module globals and constants.
Okay: import os Okay: # this is a commentnimport os Okay: '''this is a module docstring'''nimport os Okay: r'''this is a module docstring'''nimport os Okay: try:ntimport xnexcept ImportError:ntpassnelse:ntpassnimport y Okay: try:ntimport xnexcept ImportError:ntpassnfinally:ntpassnimport y E402: a=1nimport os E402: 'One string'n"Two string"nimport os E402: a=1nfrom sys import x
Okay: if x:n import os
Replace contents with 'xxx' to prevent syntax matching.
>>> mute_string('"abc"') '"xxx"' >>> mute_string("'''abc'''") "'''xxx'''" >>> mute_string("r'abc'") "r'xxx'"
Process options passed either via arglist or command line args.
Passing in the config_file parameter allows other tools, such as flake8 to specify their own options to be processed in pycodestyle.
'async' and 'await' are reserved keywords starting at Python 3.7.
W606: async = 42 W606: await = 42 Okay: async def read(db): data = await db.fetch('SELECT ...')
The {}.has_key() method is removed in Python 3: use the 'in' operator.
Okay: if "alph" in d:n print d["alph"] W601: assert d.has_key('alph')
New code should always use != instead of <>.
The older syntax is removed in Python 3.
Okay: if a != 'no': W603: if a <> 'no':
When raising an exception, use "raise ValueError('message')".
The older form is removed in Python 3.
Okay: raise DummyError("Message") W602: raise DummyError, "Message"
Read and parse configurations.
If a config file is specified on the command line with the "--config" option, then only it is used for configuration.
Otherwise, the user configuration (~/.config/pycodestyle) and any local configurations in the current directory or above will be merged together (in that order) using the read method of ConfigParser.
On new projects, spaces-only are strongly recommended over tabs.
Okay: if True:n return W191: if True:ntreturn
Never mix tabs and spaces.
The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!
Okay: if a == 0:n a = 1n b = 1 E101: if a == 0:n a = 1ntb = 1
Trailing blank lines are superfluous.
Okay: spam(1) W391: spam(1)n
However the last line should end with a new line (warning W292).
Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank, for easier filtering for those who want to indent their blank lines.
Okay: spam(1)n# W291: spam(1) n# W293: class Foo(object):n n bang = 12
Avoid extraneous whitespace after a comma or a colon.
Note: these checks are disabled by default
Okay: a = (1, 2) E241: a = (1, 2) E242: a = (1,t2)
Avoid extraneous whitespace around keywords.
Okay: True and False E271: True and False E272: True and False E273: True andtFalse E274: Truetand False
Don't use spaces around the '=' sign in function arguments.
Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value, except when using a type annotation.
Okay: def complex(real, imag=0.0): Okay: return magic(r=real, i=imag) Okay: boolean(a == b) Okay: boolean(a != b) Okay: boolean(a <= b) Okay: boolean(a >= b) Okay: def foo(arg: int = 42): Okay: async def foo(arg: int = 42):
E251: def complex(real, imag = 0.0): E251: return magic(r = real, i = imag) E252: def complex(real, image: float=0.0):
Avoid extraneous whitespace around an operator.
Okay: a = 12 + 3 E221: a = 4 + 5 E222: a = 4 + 5 E223: a = 4t+ 5 E224: a = 4 +t5
Separate inline comments by at least two spaces.
An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.
Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).
Okay: x = x + 1 # Increment x Okay: x = x + 1 # Increment x Okay: # Block comment E261: x = x + 1 # Increment x E262: x = x + 1 #Increment x E262: x = x + 1 # Increment x E265: #Block comment E266: ### Block comment
Avoid extraneous whitespace.
Avoid extraneous whitespace in the following situations: - before the open parenthesis that starts the argument list of a
function call.
- before the open parenthesis that starts an indexing or slicing.
Okay: spam(1) E211: spam (1)
Okay: dict['key'] = list[index] E211: dict ['key'] = list[index] E211: dict['key'] = list [index]
Undocumented
Value |
|
Undocumented
Value |
|
Undocumented
Value |
|
Undocumented
Value |
|
Undocumented
Value |
|
Private function to reduce duplication.
This factors out the shared details between
break_before_binary_operator
and
break_after_binary_operator
.