pep8 — Phatch v0.2 documentation

### Navigation

- index
- modules |
- next |
- previous |
- Phatch v0.2 documentation »
- other »

# pep8

Check Python source code formatting, according to PEP 8: http://www.python.org/dev/peps/pep-0008/

For usage and a list of options, try this: $ python pep8.py -h

This program and its regression test suite live here: http://github.com/jcrocholl/pep8

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

You can add checks to this program by writing plugins. Each plugin is a simple function that is called for each line of source code, either physical or logical.

Physical line: - Raw line of text from the input file.

Logical line: - Multi-line statements converted to a single line. - Stripped left and right. - Contents of strings replaced with ‘xxx’ of same length. - Comments removed.

The check function requests physical or logical lines by the name of the first argument:

def maximum_line_length(physical_line) def extraneous_whitespace(logical_line) def blank_lines(logical_line, blank_lines, indent_level, line_number)

The last example above demonstrates how check plugins can request additional information with extra arguments. All attributes of the Checker object are available. Some examples:

lines: a list of the raw lines from the input file tokens: the tokens that contribute to this logical line line_number: line number in the input file blank_lines: blank lines before this one indent_char: first indentation character in this file (‘ ‘ or ‘ ‘) indent_level: indentation (with tabs expanded to multiples of 8) previous_indent_level: indentation on previous line previous_logical: previous logical line

The docstring of each check function shall be the relevant part of text from PEP 8. It is printed if the user enables –show-pep8. Several docstrings contain examples directly from the PEP 8 document.

Okay: spam(ham[1], {eggs: 2}) E201: spam( ham[1], {eggs: 2})

These examples are verified automatically when pep8.py is run with the –doctest option. You can add examples for your own check functions. The format is simple: “Okay” or error/warning code followed by colon and space, the rest of the line is example source code. If you put ‘r’ before the docstring, you can use

> for newline, for tab and s

for space.

class `other.pep8.` `Checker`(filename)

  Bases: `object`

  Load a Python source file, tokenize it, check coding style.

  `build_tokens_line`()
    Build a logical line from tokens.
  `check_all`()
    Run all checks on the input file.
  `check_logical`()
    Build a line from tokens and run all logical checks on it.
  `check_physical`(line)
    Run all physical checks on a raw input line.
  `readline`()
    Get the next line from the input buffer.
  `readline_check_physical`()
    Check and return the next physical line. This method can be used to feed tokenize.generate_tokens.
  `report_error`(line_number, offset, text, check)
    Report an error, according to options.
  `run_check`(check, argument_names)
    Run a check plugin.

`other.pep8.` `blank_lines`(logical_line, blank_lines, indent_level, line_number, previous_logical, blank_lines_before_comment)

  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 passnnn# Foon# Barnndef b():n pass

  E301: class Foo:n b = 0n def bar():n pass E302: def a():n passnndef b(n):n pass E303: def a():n passnnnndef b(n):n pass E303: def a():nnnn pass E304: @decoratornndef a():n pass

`other.pep8.` `compound_statements`(logical_line)

  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()

`other.pep8.` `excluded`(filename)
  Check if options.exclude contains a pattern that matches filename.

`other.pep8.` `expand_indent`(line)

  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

`other.pep8.` `extraneous_whitespace`(logical_line)

  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

`other.pep8.` `filename_match`(filename)
  Check if options.filename contains a pattern that matches filename. If options.filename is unspecified, this always returns True.

`other.pep8.` `find_checks`(argument_name)
  Find all globally visible functions where the first argument name starts with argument_name.

`other.pep8.` `get_count`(prefix='')
  Return the total count of errors and warnings.

`other.pep8.` `get_error_statistics`()
  Get error statistics.

`other.pep8.` `get_statistics`(prefix='')

  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

`other.pep8.` `get_warning_statistics`()
  Get warning statistics.

`other.pep8.` `ignore_code`(code)
  Check if options.ignore contains a prefix of the error code. If options.select contains a prefix of the error code, do not ignore it.

`other.pep8.` `imports_on_separate_lines`(logical_line)

  Imports should usually be 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

`other.pep8.` `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

  Okay: for item in items:n pass E112: for item in items:npass

  Okay: a = 1nb = 2 E113: a = 1n b = 2

`other.pep8.` `input_dir`(dirname)
  Check all Python source files in this directory and all subdirectories.

`other.pep8.` `input_file`(filename)
  Run all checks on a Python source file.

`other.pep8.` `iskeyword`()
  x.__contains__(y) <==> y in x.

`other.pep8.` `maximum_line_length`(physical_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.

`other.pep8.` `message`(text)
  Print a message.

`other.pep8.` `missing_newline`(physical_line)
  JCR: The last line should have a newline.

`other.pep8.` `missing_whitespace`(logical_line)

  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)

`other.pep8.` `missing_whitespace_around_operator`(logical_line, tokens)
  - 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: baz(**kwargs) Okay: negative = -1 Okay: spam(-1) Okay: alpha[:-i] Okay: if not -5 < x < +5:n pass Okay: lambda *args, **kw: (args, kw)

  E225: i=i+1 E225: submitted +=1 E225: x = x*2 - 1 E225: hypot2 = x*x + y*y E225: c = (a+b) * (a-b) E225: c = alpha -4 E225: z = x **y

`other.pep8.` `mute_string`(text)

  Replace contents with ‘xxx’ to prevent syntax matching.

      >>> mute_string('"abc"')
      '"xxx"'
      >>> mute_string("'''abc'''")
      "'''xxx'''"
      >>> mute_string("r'abc'")
      "r'xxx'"

`other.pep8.` `print_benchmark`(elapsed)
  Print benchmark numbers.

`other.pep8.` `print_statistics`(prefix='')
  Print overall statistics (number of errors and warnings).

`other.pep8.` `process_options`(arglist=None)
  Process options passed either via arglist or via command line args.

`other.pep8.` `python_3000_backticks`(logical_line)
  Backticks are removed in Python 3000. Use repr() instead.

`other.pep8.` `python_3000_has_key`(logical_line)

  The {}.has_key() method will be removed in the future version of Python. Use the ‘in’ operation instead, like: d = {“a”: 1, “b”: 2} if “b” in d:

  > print d[“b”]

`other.pep8.` `python_3000_not_equal`(logical_line)
  != 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 3000.

`other.pep8.` `python_3000_raise_comma`(logical_line)

  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 will be removed in Python 3000.

`other.pep8.` `selftest`()
  Test all check functions with test cases in docstrings.

`other.pep8.` `tabs_obsolete`(physical_line)

  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:ntreturn

`other.pep8.` `tabs_or_spaces`(physical_line, indent_char)

  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

`other.pep8.` `trailing_blank_lines`(physical_line, lines, line_number)

  JCR: Trailing blank lines are superfluous.

  Okay: spam(1) W391: spam(1)n

`other.pep8.` `trailing_whitespace`(physical_line)

  JCR: Trailing whitespace is superfluous.

  Okay: spam(1) W291: spam(1)s

`other.pep8.` `whitespace_around_comma`(logical_line)

  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, 2)

`other.pep8.` `whitespace_around_named_parameter_equals`(logical_line)

  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)

`other.pep8.` `whitespace_around_operator`(logical_line)

  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 + 5 E224: a = 4 + 5

`other.pep8.` `whitespace_before_inline_comment`(logical_line, tokens)

  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

`other.pep8.` `whitespace_before_parameters`(logical_line, tokens)

  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]

### Navigation

- index
- modules |
- next |
- previous |
- Phatch v0.2 documentation »
- other »