ARITHMETIC_OP |
BENCHMARK_KEYS |
COMMENT_WITH_NL |
COMPARE_SINGLETON_REGEX |
COMPARE_TYPE_REGEX |
DEFAULT_EXCLUDE |
DEFAULT_IGNORE |
DOCSTRING_REGEX |
ERRORCODE_REGEX |
EXTRANEOUS_WHITESPACE_REGEX |
HUNK_REGEX |
INDENT_REGEX |
KEYWORDS |
KEYWORD_REGEX |
LAMBDA_REGEX |
MAX_LINE_LENGTH |
OPERATOR_REGEX |
PROJECT_CONFIG |
PyCF_ONLY_AST |
RAISE_COMMA_REGEX |
REPORT_FORMAT |
RERAISE_COMMA_REGEX |
SINGLETONS |
SKIP_TOKENS |
TESTSUITE_PATH |
UNARY_OPERATORS |
WHITESPACE |
WHITESPACE_AFTER_COMMA_REGEX |
WS_NEEDED_OPERATORS |
WS_OPTIONAL_OPERATORS |
__version__ |
_checks |
noqa |
BaseReport | Collect the results of the checks. |
Checker | Load a Python source file, tokenize it, check coding style. |
DiffReport | Collect and print the results for the changed lines only. |
FileReport | Collect the results of the checks and print only the filenames. |
StandardReport | Collect and print the results of the checks. |
StyleGuide | Initialize a PEP-8 instance with few options. |
_add_check | |
_main | Parse options and run checks on Python source. |
blank_lines | Separate top-level function and class definitions with two blank lines. |
comparison_to_singleton | Comparisons to singletons like None should always be done with "is" or "is not", never the equality operators. |
comparison_type | Object type comparisons should always use isinstance() instead of comparing types directly. |
compound_statements | Compound statements (multiple statements on the same line) are generally discouraged. |
continued_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. |
expand_indent | Return the amount of indentation. |
explicit_line_join | Avoid explicit line join between brackets. |
extraneous_whitespace | Avoid extraneous whitespace in the following situations: |
filename_match | Check if patterns contains a pattern that matches filename. |
get_parser | |
imports_on_separate_lines | Imports should usually be on separate lines. |
indentation | Use 4 spaces per indentation level. |
init_checks_registry | Register all globally visible functions where the first argument name is 'physical_line' or 'logical_line'. |
maximum_line_length | Limit all lines to a maximum of 79 characters. |
missing_newline | JCR: The last line should have a newline. |
missing_whitespace | JCR: Each comma, semicolon or colon should be followed by whitespace. |
missing_whitespace_around_operator | - 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). |
mute_string | Replace contents with 'xxx' to prevent syntax matching. |
parse_udiff | Return a dictionary of matching lines. |
process_options | Process options passed either via arglist or via command line args. |
python_3000_backticks | Backticks are removed in Python 3. |
python_3000_has_key | The {}.has_key() method is removed in the Python 3. |
python_3000_not_equal | != can also be written <>, but this is an obsolete usage kept for backwards compatibility only. |
python_3000_raise_comma | When raising an exception, use "raise ValueError('message')" instead of the older form "raise ValueError, 'message'". |
read_config | Read both user configuration and local configuration. |
readlines | |
readlines | |
register_check | Register a new check object. |
stdin_get_value | |
tabs_obsolete | For new projects, spaces-only are strongly recommended over tabs. |
tabs_or_spaces | Never mix tabs and spaces. |
trailing_blank_lines | JCR: Trailing blank lines are superfluous. |
trailing_whitespace | JCR: Trailing whitespace is superfluous. |
whitespace_around_comma | Avoid extraneous whitespace in the following situations: |
whitespace_around_keywords | Avoid extraneous whitespace around keywords. |
whitespace_around_named_parameter_equals | Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value. |
whitespace_around_operator | Avoid extraneous whitespace in the following situations: |
whitespace_before_inline_comment | Separate inline comments by at least two spaces. |
whitespace_before_parameters | Avoid extraneous whitespace in the following situations: |
Collect the results of the checks.
print_filename |
None |
BaseReport | |
error | Report an error, according to options. |
error_args | Report an error, according to options. |
get_count | Return the total count of errors and warnings. |
get_file_results | Return the count of errors and warnings for this file. |
get_statistics | Get statistics for message codes that start with the prefix. |
increment_logical_line | Signal a new logical line. |
init_file | Signal a new file. |
print_benchmark | Print benchmark numbers. |
print_statistics | Print overall statistics (number of errors and warnings). |
start | Start the timer. |
stop | Stop the timer. |
None |
Report an error, according to options.
Report an error, according to options.
Return the total count of errors and warnings.
Return the count of errors and warnings for this file.
Get statistics for message codes that start with the prefix.
prefix='' matches all errors and warnings prefix='E' matches all errors prefix='W' matches all warnings prefix='E4' matches all errors that have to do with imports
Signal a new logical line.
Signal a new file.
Print benchmark numbers.
Print overall statistics (number of errors and warnings).
Start the timer.
Stop the timer.
Load a Python source file, tokenize it, check coding style.
None |
None |
Checker | |
build_tokens_line | Build a logical line from tokens. |
check_all | Run all checks on the input file. |
check_ast | |
check_logical | Build a line from tokens and run all logical checks on it. |
check_physical | Run all physical checks on a raw input line. |
generate_tokens | |
readline | Get the next line from the input buffer. |
readline_check_physical | Check and return the next physical line. |
report_invalid_syntax | |
run_check | Run a check plugin. |
None |
Build a logical line from tokens.
Run all checks on the input file.
Build a line from tokens and run all logical checks on it.
Run all physical checks on a raw input line.
Get the next line from the input buffer.
Check and return the next physical line. This method can be used to feed tokenize.generate_tokens.
Run a check plugin.
Collect and print the results for the changed lines only.
None |
None |
DiffReport | |
error |
None |
Collect the results of the checks and print only the filenames.
print_filename |
None |
None |
None |
Collect and print the results of the checks.
None |
None |
StandardReport | |
error | Report an error, according to options. |
error_args | Report an error, according to options. |
get_file_results | Print the result and return the overall count for this file. |
init_file | Signal a new file. |
None |
Report an error, according to options.
Report an error, according to options.
Print the result and return the overall count for this file.
Signal a new file.
Initialize a PEP-8 instance with few options.
None |
None |
StyleGuide | |
check_files | Run all checks on the paths. |
excluded | Check if options.exclude contains a pattern that matches filename. |
get_checks | Find all globally visible functions where the first argument name starts with argument_name and which contain selected tests. |
ignore_code | Check if the error code should be ignored. |
init_report | Initialize the report instance. |
input_dir | Check all files in this directory and all subdirectories. |
input_file | Run all checks on a Python source file. |
None |
Run all checks on the paths.
Check if options.exclude contains a pattern that matches filename.
Find all globally visible functions where the first argument name starts with argument_name and which contain selected tests.
Check if the error code should be ignored.
If 'options.select' contains a prefix of the error code, return False. Else, if 'options.ignore' contains a prefix of the error code, return True.
Initialize the report instance.
Check all files in this directory and all subdirectories.
Run all checks on a Python source file.
Parse options and run checks on Python source.
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 pass\n\n\ndef b():\n pass Okay: def a():\n pass\n\n\n# Foo\n# Bar\n\ndef b():\n pass
E301: class Foo:\n b = 0\n def bar():\n pass E302: def a():\n pass\n\ndef b(n):\n pass E303: def a():\n pass\n\n\n\ndef b(n):\n pass E303: def a():\n\n\n\n pass E304: @decorator\n\ndef a():\n pass
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: E712: if arg == True:
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() instead of comparing 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 (multiple 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!
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
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 the following 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 42\n ) E124: a = (24,\n 42\n) E125: if (a or\n b):\n pass E126: a = (\n 42) E127: a = (24,\n 42) E128: a = (24,\n 42)
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') 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"
Avoid extraneous whitespace in the following 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.
Imports should usually be on separate lines.
Okay: import os\nimport 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
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
Okay: for item in items:\n pass E112: for item in items:\npass
Okay: a = 1\nb = 2 E113: a = 1\n b = 2
Register all globally visible functions where the first argument name is 'physical_line' or 'logical_line'.
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.
JCR: The last line should have a newline.
Reports warning W292.
JCR: 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'}]
- 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).
- Use spaces around arithmetic operators.
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 E226: c = (a+b) * (a-b) E226: hypot2 = x*x + y*y E227: c = a|b E228: msg = fmt%(errno, errmsg)
Replace contents with 'xxx' to prevent syntax matching.
>>> mute_string('"abc"') '"xxx"' >>> mute_string("'''abc'''") "'''xxx'''" >>> mute_string("r'abc'") "r'xxx'"
Return a dictionary of matching lines.
Process options passed either via arglist or via command line args.
Backticks are removed in Python 3. Use repr() instead.
Okay: val = repr(1 + 2) W604: val = `1 + 2`
The {}.has_key() method is removed in the Python 3. Use the 'in' operation instead.
Okay: if "alph" in d:\n print d["alph"] W601: assert d.has_key('alph')
!= can also be written <>, but this is an obsolete usage kept for backwards compatibility only. New code should always use !=. The older syntax is removed in Python 3.
Okay: if a != 'no': W603: if a <> 'no':
When raising an exception, use "raise ValueError('message')" instead of the older form "raise ValueError, 'message'".
The paren-using form is preferred because when the exception arguments are long or include string formatting, you don't need to use line continuation characters thanks to the containing parentheses. The older form is removed in Python 3.
Okay: raise DummyError("Message") W602: raise DummyError, "Message"
Read both user configuration and local configuration.
Register a new check object.
For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do.
Okay: if True:\n return W191: if True:\n\treturn
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 = 1\n b = 1 E101: if a == 0:\n a = 1\n\tb = 1
JCR: Trailing blank lines are superfluous.
Okay: spam(1) W391: spam(1)\n
JCR: Trailing whitespace is superfluous. FBM: Except when it occurs as part of a blank line (i.e. the line is nothing but whitespace). According to Python docs[1] a line with only whitespace is considered a blank line, and is to be ignored. However, matching a blank line to its indentation level avoids mistakenly terminating a multi-line statement (e.g. class declaration) when pasting code into the standard Python interpreter.
[1] http://docs.python.org/reference/lexical_analysis.html#blank-lines
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 in the following situations:
- More than one space around an assignment (or other) operator to align it with another.
JCR: This should also be applied around comma etc. 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 and\tFalse E274: True\tand False
Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value.
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)
E251: def complex(real, imag = 0.0): E251: return magic(r = real, i = imag)
Avoid extraneous whitespace in the following situations:
- More than one space around an assignment (or other) operator to align it with another.
Okay: a = 12 + 3 E221: a = 4 + 5 E222: a = 4 + 5 E223: a = 4\t+ 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.
Okay: x = x + 1 # Increment x Okay: x = x + 1 # Increment x E261: x = x + 1 # Increment x E262: x = x + 1 #Increment x E262: x = x + 1 # Increment x
Avoid extraneous whitespace in the following situations:
- Immediately before the open parenthesis that starts the argument list of a function call.
- Immediately 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]