Back to index

moin  1.9.0~rc2
Classes | Functions | Variables
MoinMoin._tests.pep8 Namespace Reference

Classes

class  Checker

Functions

def tabs_or_spaces
 Plugins (check functions) for physical lines.
def tabs_obsolete
def trailing_whitespace
def trailing_blank_lines
def missing_newline
def maximum_line_length
def crlf_lines
def blank_lines
 Plugins (check functions) for logical lines.
def extraneous_whitespace
def missing_whitespace
def indentation
def whitespace_before_parameters
def extra_whitespace_around_operator
def whitespace_around_operator
def whitespace_around_comma
def imports_on_separate_lines
def compound_statements
def python_3000_has_key
def python_3000_raise_comma
def dumb_equals_boolean
def dumb_equals_None
def expand_indent
 Helper functions.
def message
 Framework to run all checks.
def find_checks
def mute_string
def input_file
def input_dir
def excluded
def filename_match
def ignore_code
def get_error_statistics
def get_warning_statistics
def get_statistics
def print_statistics
def print_benchmark
def process_options
def _main

Variables

string __version__ = '0.2.0'
string __revision__ = '$Rev$'
string default_exclude = '.svn,CVS,*.pyc,*.pyo'
tuple indent_match = re.compile(r'([ \t]*)')
tuple raise_comma_match = re.compile(r'raise\s+\w+\s*(,)')
tuple equals_boolean_search = re.compile(r'([!=]=\s*(True|False))|((True|False)\s*[!=]=)')
tuple equals_None_search = re.compile(r'([!=]=\s*None)|(None\s*[!=]=)')
tuple not_one_ws_around_operators_match = re.compile(r'^[^\(\[]+[^\s](\+|\-|\*|/|%|\^|&|\||=|<|>|>>|<<|\+=|\-=|\*=|/=|%=|\^=|&=|\|=|==|<=|>=|>>=|<<=|!=|<>)[^\s][^\)\]]+$')
string operators
 options = None
 args = None

Function Documentation

def MoinMoin._tests.pep8._main ( ) [private]
Parse options and run checks on Python source.

Definition at line 894 of file pep8.py.

00894 
00895 def _main():
00896     """
00897     Parse options and run checks on Python source.
00898     """
00899     options, args = process_options()
00900     if options.doctest:
00901         import doctest
00902         return doctest.testmod()
00903     start_time = time.time()
00904     for path in args:
00905         if os.path.isdir(path):
00906             input_dir(path)
00907         else:
00908             input_file(path)
00909     elapsed = time.time() - start_time
00910     if options.statistics:
00911         print_statistics()
00912     if options.benchmark:
00913         print_benchmark(elapsed)
00914 

Here is the call graph for this function:

def MoinMoin._tests.pep8.blank_lines (   logical_line,
  blank_lines,
  indent_level,
  line_number,
  previous_logical 
)

Plugins (check functions) for logical 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.

Definition at line 215 of file pep8.py.

00215 
00216                 previous_logical):
00217     """
00218     Separate top-level function and class definitions with two blank lines.
00219 
00220     Method definitions inside a class are separated by a single blank line.
00221 
00222     Extra blank lines may be used (sparingly) to separate groups of related
00223     functions.  Blank lines may be omitted between a bunch of related
00224     one-liners (e.g. a set of dummy implementations).
00225 
00226     Use blank lines in functions, sparingly, to indicate logical sections.
00227     """
00228     if line_number == 1:
00229         return # Don't expect blank lines before the first line
00230     if previous_logical.startswith('@'):
00231         return # Don't expect blank lines after function decorator
00232     if (logical_line.startswith('def ') or
00233         logical_line.startswith('class ') or
00234         logical_line.startswith('@')):
00235         if indent_level > 0 and blank_lines != 1:
00236             return 0, "E301 expected 1 blank line, found %d" % blank_lines
00237         if indent_level == 0 and blank_lines != 2:
00238             return 0, "E302 expected 2 blank lines, found %d" % blank_lines
00239     if blank_lines > 2:
00240         return 0, "E303 too many blank lines (%d)" % blank_lines
00241 

Here is the caller graph for this function:

Compound statements (multiple statements on the same line) are
generally discouraged.

Definition at line 385 of file pep8.py.

00385 
00386 def compound_statements(logical_line):
00387     """
00388     Compound statements (multiple statements on the same line) are
00389     generally discouraged.
00390     """
00391     line = logical_line
00392     found = line.find(':')
00393     if -1 < found < len(line) - 1:
00394         before = line[:found]
00395         if (before.count('{') <= before.count('}') and # {'a': 1} (dict)
00396             before.count('[') <= before.count(']') and # [1:2] (slice)
00397             not re.search(r'\blambda\b', before)):     # lambda x: x
00398             return found, "E701 multiple statements on one line (colon)"
00399     found = line.find(';')
00400     if -1 < found:
00401         return found, "E702 multiple statements on one line (semicolon)"
00402 

def MoinMoin._tests.pep8.crlf_lines (   physical_line)
Line contains CR (e.g. as a CRLF line ending).

Many free software projects have a strong focus on POSIX platforms (like
Linux, *BSD, Unix, Mac OS X, etc.) and they all use LF-only line endings.
Only Win32 platform uses CRLF line endings.
So if you have a Win32-only source code using CRLF line endings, you might
want to exclude this test.

Definition at line 194 of file pep8.py.

00194 
00195 def crlf_lines(physical_line):
00196     """
00197     Line contains CR (e.g. as a CRLF line ending).
00198 
00199     Many free software projects have a strong focus on POSIX platforms (like
00200     Linux, *BSD, Unix, Mac OS X, etc.) and they all use LF-only line endings.
00201     Only Win32 platform uses CRLF line endings.
00202     So if you have a Win32-only source code using CRLF line endings, you might
00203     want to exclude this test.
00204     """
00205     pos = physical_line.find('\r')
00206     if pos >= 0:
00207         return pos, "W293 line contains CR char(s)"
00208 

Here is the call graph for this function:

Using "if x == True:" or "if x == False:" is wrong in any case:

First if you already have a boolean, you don't need to compare it to
another boolean. Just use "if x:" or "if not x:".

Second, even if you have some sort of "tristate logic", not only using
True/False, but other values, then you want to use "if x is True:" or
"if x is False:" because there is exactly one True and one False object.

Definition at line 431 of file pep8.py.

00431 
00432 def dumb_equals_boolean(logical_line):
00433     """
00434     Using "if x == True:" or "if x == False:" is wrong in any case:
00435 
00436     First if you already have a boolean, you don't need to compare it to
00437     another boolean. Just use "if x:" or "if not x:".
00438 
00439     Second, even if you have some sort of "tristate logic", not only using
00440     True/False, but other values, then you want to use "if x is True:" or
00441     "if x is False:" because there is exactly one True and one False object.
00442     """
00443     match = equals_boolean_search(logical_line)
00444     if match:
00445         return match.start(1), "E798 don't use 'x == <boolean>', but just 'x' or 'not x' or 'x is <boolean>'"
00446 

def MoinMoin._tests.pep8.dumb_equals_None (   logical_line)
Using "if x == None:" is wrong in any case:

You either want to use "if x is None:" (there is only 1 None object) or -
in some simple cases - just "if not x:".

Definition at line 447 of file pep8.py.

00447 
00448 def dumb_equals_None(logical_line):
00449     """
00450     Using "if x == None:" is wrong in any case:
00451 
00452     You either want to use "if x is None:" (there is only 1 None object) or -
00453     in some simple cases - just "if not x:".
00454     """
00455     match = equals_None_search(logical_line)
00456     if match:
00457         return match.start(1), "E799 don't use 'x == None', but just 'x is None' or 'not x'"
00458 

def MoinMoin._tests.pep8.excluded (   filename)
Check if options.exclude contains a pattern that matches filename.

Definition at line 761 of file pep8.py.

00761 
00762 def excluded(filename):
00763     """
00764     Check if options.exclude contains a pattern that matches filename.
00765     """
00766     basename = os.path.basename(filename)
00767     for pattern in options.exclude:
00768         if fnmatch(basename, pattern):
00769             # print basename, 'excluded because it matches', pattern
00770             return True
00771 

Helper functions.

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

Definition at line 464 of file pep8.py.

00464 
00465 def expand_indent(line):
00466     """
00467     Return the amount of indentation.
00468     Tabs are expanded to the next multiple of 8.
00469 
00470     >>> expand_indent('    ')
00471     4
00472     >>> expand_indent('\\t')
00473     8
00474     >>> expand_indent('    \\t')
00475     8
00476     >>> expand_indent('       \\t')
00477     8
00478     >>> expand_indent('        \\t')
00479     16
00480     """
00481     result = 0
00482     for char in line:
00483         if char == '\t':
00484             result = result / 8 * 8 + 8
00485         elif char == ' ':
00486             result += 1
00487         else:
00488             break
00489     return result
00490 

Avoid extraneous whitespace in the following situations:

- More than one space around an assignment (or other) operator to
  align it with another.

Definition at line 323 of file pep8.py.

00323 
00324 def extra_whitespace_around_operator(logical_line):
00325     """
00326     Avoid extraneous whitespace in the following situations:
00327 
00328     - More than one space around an assignment (or other) operator to
00329       align it with another.
00330     """
00331     line = logical_line
00332     for operator in operators:
00333         found = line.find('  ' + operator)
00334         if found > -1:
00335             return found, "E221 multiple spaces before operator"
00336         found = line.find(operator + '  ')
00337         if found > -1:
00338             return found, "E222 multiple spaces after operator"
00339         found = line.find('\t' + operator)
00340         if found > -1:
00341             return found, "E223 tab before operator"
00342         found = line.find(operator + '\t')
00343         if found > -1:
00344             return found, "E224 tab after operator"
00345 

Avoid extraneous whitespace in the following situations:

- Immediately inside parentheses, brackets or braces.

- Immediately before a comma, semicolon, or colon.

Definition at line 242 of file pep8.py.

00242 
00243 def extraneous_whitespace(logical_line):
00244     """
00245     Avoid extraneous whitespace in the following situations:
00246 
00247     - Immediately inside parentheses, brackets or braces.
00248 
00249     - Immediately before a comma, semicolon, or colon.
00250     """
00251     line = logical_line
00252     for char in '([{':
00253         found = line.find(char + ' ')
00254         if found > -1:
00255             return found + 1, "E201 whitespace after '%s'" % char
00256     for char in '}])':
00257         found = line.find(' ' + char)
00258         if found > -1 and line[found - 1] != ',':
00259             return found, "E202 whitespace before '%s'" % char
00260     for char in ',;:':
00261         found = line.find(' ' + char)
00262         if found > -1:
00263             return found, "E203 whitespace before '%s'" % char
00264 

Check if options.filename contains a pattern that matches filename.
If options.filename is unspecified, this always returns True.

Definition at line 772 of file pep8.py.

00772 
00773 def filename_match(filename):
00774     """
00775     Check if options.filename contains a pattern that matches filename.
00776     If options.filename is unspecified, this always returns True.
00777     """
00778     if not options.filename:
00779         return True
00780     for pattern in options.filename:
00781         if fnmatch(filename, pattern):
00782             return True
00783 

def MoinMoin._tests.pep8.find_checks (   argument_name)
Find all globally visible functions where the first argument name
starts with argument_name.

Definition at line 503 of file pep8.py.

00503 
00504 def find_checks(argument_name):
00505     """
00506     Find all globally visible functions where the first argument name
00507     starts with argument_name.
00508     """
00509     checks = []
00510     function_type = type(find_checks)
00511     for name, function in globals().iteritems():
00512         if type(function) is function_type:
00513             args = inspect.getargspec(function)[0]
00514             if len(args) >= 1 and args[0].startswith(argument_name):
00515                 checks.append((name, function, args))
00516     checks.sort()
00517     return checks
00518 

Get error statistics.

Definition at line 793 of file pep8.py.

00793 
00794 def get_error_statistics():
00795     """Get error statistics."""
00796     return get_statistics("E")
00797 

Here is the call graph for this function:

def MoinMoin._tests.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

Definition at line 803 of file pep8.py.

00803 
00804 def get_statistics(prefix=''):
00805     """
00806     Get statistics for message codes that start with the prefix.
00807 
00808     prefix='' matches all errors and warnings
00809     prefix='E' matches all errors
00810     prefix='W' matches all warnings
00811     prefix='E4' matches all errors that have to do with imports
00812     """
00813     stats = []
00814     keys = options.messages.keys()
00815     keys.sort()
00816     for key in keys:
00817         if key.startswith(prefix):
00818             stats.append('%-7s %s %s' %
00819                          (options.counters[key], key, options.messages[key]))
00820     return stats
00821 

Here is the caller graph for this function:

Get warning statistics.

Definition at line 798 of file pep8.py.

00798 
00799 def get_warning_statistics():
00800     """Get warning statistics."""
00801     return get_statistics("W")
00802 

Here is the call graph for this function:

Check if options.ignore contains a prefix of the error code.

Definition at line 784 of file pep8.py.

00784 
00785 def ignore_code(code):
00786     """
00787     Check if options.ignore contains a prefix of the error code.
00788     """
00789     for ignore in options.ignore:
00790         if code.startswith(ignore):
00791             return True
00792 

Imports should usually be on separate lines.

Definition at line 374 of file pep8.py.

00374 
00375 def imports_on_separate_lines(logical_line):
00376     """
00377     Imports should usually be on separate lines.
00378     """
00379     line = logical_line
00380     if line.startswith('import '):
00381         found = line.find(',')
00382         if found > -1:
00383             return found, "E401 multiple imports on one line"
00384 

def MoinMoin._tests.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.

Definition at line 280 of file pep8.py.

00280 
00281                 indent_level, previous_indent_level):
00282     """
00283     Use 4 spaces per indentation level.
00284 
00285     For really old code that you don't want to mess up, you can continue to
00286     use 8-space tabs.
00287     """
00288     if indent_char == ' ' and indent_level % 4:
00289         return 0, "E111 indentation is not a multiple of four"
00290     indent_expect = previous_logical.endswith(':')
00291     if indent_expect and indent_level <= previous_indent_level:
00292         return 0, "E112 expected an indented block"
00293     if indent_level > previous_indent_level and not indent_expect:
00294         return 0, "E113 unexpected indentation"
00295 

Here is the caller graph for this function:

def MoinMoin._tests.pep8.input_dir (   dirname)
Check all Python source files in this directory and all subdirectories.

Definition at line 740 of file pep8.py.

00740 
00741 def input_dir(dirname):
00742     """
00743     Check all Python source files in this directory and all subdirectories.
00744     """
00745     dirname = dirname.rstrip('/')
00746     if excluded(dirname):
00747         return
00748     for root, dirs, files in os.walk(dirname):
00749         if options.verbose:
00750             message('directory ' + root)
00751         options.counters['directories'] = \
00752             options.counters.get('directories', 0) + 1
00753         dirs.sort()
00754         for subdir in dirs:
00755             if excluded(subdir):
00756                 dirs.remove(subdir)
00757         files.sort()
00758         for filename in files:
00759             input_file(os.path.join(root, filename))
00760 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin._tests.pep8.input_file (   filename)
Run all checks on a Python source file.

Definition at line 726 of file pep8.py.

00726 
00727 def input_file(filename):
00728     """
00729     Run all checks on a Python source file.
00730     """
00731     if excluded(filename) or not filename_match(filename):
00732         return {}
00733     if options.verbose:
00734         message('checking ' + filename)
00735     options.counters['files'] = options.counters.get('files', 0) + 1
00736     errors = Checker(filename).check_all()
00737     if options.testsuite and not errors:
00738         message("%s: %s" % (filename, "no errors found"))
00739 

Here is the call graph for this function:

Here is the caller graph for this function:

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.

Definition at line 178 of file pep8.py.

00178 
00179 def maximum_line_length(physical_line):
00180     """
00181     Limit all lines to a maximum of 79 characters.
00182 
00183     There are still many devices around that are limited to 80 character
00184     lines; plus, limiting windows to 80 characters makes it possible to have
00185     several windows side-by-side.  The default wrapping on such devices looks
00186     ugly.  Therefore, please limit all lines to a maximum of 79 characters.
00187     For flowing long blocks of text (docstrings or comments), limiting the
00188     length to 72 characters is recommended.
00189     """
00190     length = len(physical_line.rstrip())
00191     if length > 79:
00192         return 79, "E501 line too long (%d characters)" % length
00193 

Framework to run all checks.

Print a message.

Definition at line 496 of file pep8.py.

00496 
00497 def message(text):
00498     """Print a message."""
00499     # print >> sys.stderr, options.prog + ': ' + text
00500     # print >> sys.stderr, text
00501     print text
00502 

Here is the caller graph for this function:

def MoinMoin._tests.pep8.missing_newline (   physical_line)
JCR: The last line should have a newline.

Definition at line 170 of file pep8.py.

00170 
00171 def missing_newline(physical_line):
00172     """
00173     JCR: The last line should have a newline.
00174     """
00175     if physical_line.rstrip() == physical_line:
00176         return len(physical_line), "W292 no newline at end of file"
00177 

JCR: Each comma, semicolon or colon should be followed by whitespace.

Definition at line 265 of file pep8.py.

00265 
00266 def missing_whitespace(logical_line):
00267     """
00268     JCR: Each comma, semicolon or colon should be followed by whitespace.
00269     """
00270     line = logical_line
00271     for index in range(len(line) - 1):
00272         char = line[index]
00273         if char in ',;:' and line[index + 1] != ' ':
00274             before = line[:index]
00275             if char == ':' and before.count('[') > before.count(']'):
00276                 continue # Slice syntax, no space required
00277             return index, "E231 missing whitespace after '%s'" % char
00278 

Here is the call graph for this function:

Replace contents with 'xxx' to prevent syntax matching.

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

Definition at line 519 of file pep8.py.

00519 
00520 def mute_string(text):
00521     """
00522     Replace contents with 'xxx' to prevent syntax matching.
00523 
00524     >>> mute_string('"abc"')
00525     '"xxx"'
00526     >>> mute_string("'''abc'''")
00527     "'''xxx'''"
00528     >>> mute_string("r'abc'")
00529     "r'xxx'"
00530     """
00531     start = 1
00532     end = len(text) - 1
00533     # String modifiers (e.g. u or r)
00534     if text.endswith('"'):
00535         start += text.index('"')
00536     elif text.endswith("'"):
00537         start += text.index("'")
00538     # Triple quotes
00539     if text.endswith('"""') or text.endswith("'''"):
00540         start += 2
00541         end -= 2
00542     return text[:start] + 'x' * (end - start) + text[end:]
00543 

Print benchmark numbers.

Definition at line 828 of file pep8.py.

00828 
00829 def print_benchmark(elapsed):
00830     """
00831     Print benchmark numbers.
00832     """
00833     print '%-7.2f %s' % (elapsed, 'seconds elapsed')
00834     keys = ['directories', 'files',
00835             'logical lines', 'physical lines']
00836     for key in keys:
00837         if key in options.counters:
00838             print '%-7d %s per second (%d total)' % (
00839                 options.counters[key] / elapsed, key,
00840                 options.counters[key])
00841 

Here is the caller graph for this function:

Print overall statistics (number of errors and warnings).

Definition at line 822 of file pep8.py.

00822 
00823 def print_statistics(prefix=''):
00824     """Print overall statistics (number of errors and warnings)."""
00825     for line in get_statistics(prefix):
00826         print line
00827 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin._tests.pep8.process_options (   arglist = None)
Process options passed either via arglist or via command line args.

Definition at line 842 of file pep8.py.

00842 
00843 def process_options(arglist=None):
00844     """
00845     Process options passed either via arglist or via command line args.
00846     """
00847     global options, args
00848     usage = "%prog [options] input ..."
00849     parser = OptionParser(usage)
00850     parser.add_option('-v', '--verbose', default=0, action='count',
00851                       help="print status messages, or debug with -vv")
00852     parser.add_option('-q', '--quiet', default=0, action='count',
00853                       help="report only file names, or nothing with -qq")
00854     parser.add_option('--exclude', metavar='patterns', default=default_exclude,
00855                       help="skip matches (default %s)" % default_exclude)
00856     parser.add_option('--filename', metavar='patterns',
00857                       help="only check matching files (e.g. *.py)")
00858     parser.add_option('--ignore', metavar='errors', default='',
00859                       help="skip errors and warnings (e.g. E4,W)")
00860     parser.add_option('--repeat', action='store_true',
00861                       help="show all occurrences of the same error")
00862     parser.add_option('--show-source', action='store_true',
00863                       help="show source code for each error")
00864     parser.add_option('--show-pep8', action='store_true',
00865                       help="show text of PEP 8 for each error")
00866     parser.add_option('--statistics', action='store_true',
00867                       help="count errors and warnings")
00868     parser.add_option('--benchmark', action='store_true',
00869                       help="measure processing speed")
00870     parser.add_option('--testsuite', metavar='dir',
00871                       help="run regression tests from dir")
00872     parser.add_option('--doctest', action='store_true',
00873                       help="run doctest on myself")
00874     options, args = parser.parse_args(arglist)
00875     if options.testsuite:
00876         args.append(options.testsuite)
00877     if len(args) == 0:
00878         parser.error('input not specified')
00879     options.prog = os.path.basename(sys.argv[0])
00880     options.exclude = options.exclude.split(',')
00881     for index in range(len(options.exclude)):
00882         options.exclude[index] = options.exclude[index].rstrip('/')
00883     if options.filename:
00884         options.filename = options.filename.split(',')
00885     if options.ignore:
00886         options.ignore = options.ignore.split(',')
00887     else:
00888         options.ignore = []
00889     options.counters = {}
00890     options.messages = {}
00891 
00892     return options, args
00893 

Here is the caller graph for this function:

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"]

Definition at line 403 of file pep8.py.

00403 
00404 def python_3000_has_key(logical_line):
00405     """
00406     The {}.has_key() method will be removed in the future version of
00407     Python. Use the 'in' operation instead, like:
00408     d = {"a": 1, "b": 2}
00409     if "b" in d:
00410         print d["b"]
00411     """
00412     pos = logical_line.find('.has_key(')
00413     if pos > -1:
00414         return pos, "W601 .has_key() is deprecated, use 'in'"
00415 

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.

Definition at line 416 of file pep8.py.

00416 
00417 def python_3000_raise_comma(logical_line):
00418     """
00419     When raising an exception, use "raise ValueError('message')"
00420     instead of the older form "raise ValueError, 'message'".
00421 
00422     The paren-using form is preferred because when the exception arguments
00423     are long or include string formatting, you don't need to use line
00424     continuation characters thanks to the containing parentheses.  The older
00425     form will be removed in Python 3000.
00426     """
00427     match = raise_comma_match(logical_line)
00428     if match:
00429         return match.start(1), "W602 deprecated form of raising exception"
00430 

def MoinMoin._tests.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.

Definition at line 140 of file pep8.py.

00140 
00141 def tabs_obsolete(physical_line):
00142     """
00143     For new projects, spaces-only are strongly recommended over tabs.  Most
00144     editors have features that make this easy to do.
00145     """
00146     indent = indent_match(physical_line).group(1)
00147     if indent.count('\t'):
00148         return indent.index('\t'), "W191 indentation contains tabs"
00149 

def MoinMoin._tests.pep8.tabs_or_spaces (   physical_line,
  indent_char 
)

Plugins (check functions) for physical lines.

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!

Definition at line 123 of file pep8.py.

00123 
00124 def tabs_or_spaces(physical_line, indent_char):
00125     """
00126     Never mix tabs and spaces.
00127 
00128     The most popular way of indenting Python is with spaces only.  The
00129     second-most popular way is with tabs only.  Code indented with a mixture
00130     of tabs and spaces should be converted to using spaces exclusively.  When
00131     invoking the Python command line interpreter with the -t option, it issues
00132     warnings about code that illegally mixes tabs and spaces.  When using -tt
00133     these warnings become errors.  These options are highly recommended!
00134     """
00135     indent = indent_match(physical_line).group(1)
00136     for offset, char in enumerate(indent):
00137         if char != indent_char:
00138             return offset, "E101 indentation contains mixed spaces and tabs"
00139 

def MoinMoin._tests.pep8.trailing_blank_lines (   physical_line,
  lines,
  line_number 
)
JCR: Trailing blank lines are superfluous.

Definition at line 162 of file pep8.py.

00162 
00163 def trailing_blank_lines(physical_line, lines, line_number):
00164     """
00165     JCR: Trailing blank lines are superfluous.
00166     """
00167     if physical_line.strip() == '' and line_number == len(lines):
00168         return 0, "W391 blank line at end of file"
00169 

JCR: Trailing whitespace is superfluous.

Definition at line 150 of file pep8.py.

00150 
00151 def trailing_whitespace(physical_line):
00152     """
00153     JCR: Trailing whitespace is superfluous.
00154     """
00155     physical_line = physical_line.rstrip('\n') # chr(10), newline
00156     physical_line = physical_line.rstrip('\r') # chr(13), carriage return
00157     physical_line = physical_line.rstrip('\x0c') # chr(12), form feed, ^L
00158     stripped = physical_line.rstrip()
00159     if physical_line != stripped:
00160         return len(stripped), "W291 trailing whitespace"
00161 

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.

Definition at line 355 of file pep8.py.

00355 
00356 def whitespace_around_comma(logical_line):
00357     """
00358     Avoid extraneous whitespace in the following situations:
00359 
00360     - More than one space around an assignment (or other) operator to
00361       align it with another.
00362 
00363     JCR: This should also be applied around comma etc.
00364     """
00365     line = logical_line
00366     for separator in ',;:':
00367         found = line.find(separator + '  ')
00368         if found > -1:
00369             return found + 1, "E241 multiple spaces after '%s'" % separator
00370         found = line.find(separator + '\t')
00371         if found > -1:
00372             return found + 1, "E242 tab after '%s'" % separator
00373 

Have exactly 1 space left and right of the operator.

Definition at line 346 of file pep8.py.

00346 
00347 def whitespace_around_operator(logical_line):
00348     """
00349     Have exactly 1 space left and right of the operator.
00350     """
00351     match = not_one_ws_around_operators_match(logical_line)
00352     if match and not 'lambda' in logical_line:
00353         return match.start(1), "E225 operators shall be surrounded by a single space on each side %s" % logical_line
00354 

def MoinMoin._tests.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.

Definition at line 296 of file pep8.py.

00296 
00297 def whitespace_before_parameters(logical_line, tokens):
00298     """
00299     Avoid extraneous whitespace in the following situations:
00300 
00301     - Immediately before the open parenthesis that starts the argument
00302       list of a function call.
00303 
00304     - Immediately before the open parenthesis that starts an indexing or
00305       slicing.
00306     """
00307     prev_type = tokens[0][0]
00308     prev_text = tokens[0][1]
00309     prev_end = tokens[0][3]
00310     for index in range(1, len(tokens)):
00311         token_type, text, start, end, line = tokens[index]
00312         if (token_type == tokenize.OP and
00313             text in '([' and
00314             start != prev_end and
00315             prev_type == tokenize.NAME and
00316             (index < 2 or tokens[index - 2][1] != 'class') and
00317             (not iskeyword(prev_text))):
00318             return prev_end, "E211 whitespace before '%s'" % text
00319         prev_type = token_type
00320         prev_text = text
00321         prev_end = end
00322 


Variable Documentation

Definition at line 96 of file pep8.py.

Definition at line 95 of file pep8.py.

Definition at line 115 of file pep8.py.

string MoinMoin._tests.pep8.default_exclude = '.svn,CVS,*.pyc,*.pyo'

Definition at line 98 of file pep8.py.

tuple MoinMoin._tests.pep8.equals_boolean_search = re.compile(r'([!=]=\s*(True|False))|((True|False)\s*[!=]=)')

Definition at line 102 of file pep8.py.

tuple MoinMoin._tests.pep8.equals_None_search = re.compile(r'([!=]=\s*None)|(None\s*[!=]=)')

Definition at line 103 of file pep8.py.

tuple MoinMoin._tests.pep8.indent_match = re.compile(r'([ \t]*)')

Definition at line 100 of file pep8.py.

tuple MoinMoin._tests.pep8.not_one_ws_around_operators_match = re.compile(r'^[^\(\[]+[^\s](\+|\-|\*|/|%|\^|&|\||=|<|>|>>|<<|\+=|\-=|\*=|/=|%=|\^=|&=|\|=|==|<=|>=|>>=|<<=|!=|<>)[^\s][^\)\]]+$')

Definition at line 105 of file pep8.py.

Initial value:
00001 """
00002 +  -  *  /  %  ^  &  |  =  <  >  >>  <<
00003 += -= *= /= %= ^= &= |= == <= >= >>= <<=
00004 != <> :
00005 in is or not and
00006 """

Definition at line 107 of file pep8.py.

Definition at line 114 of file pep8.py.

tuple MoinMoin._tests.pep8.raise_comma_match = re.compile(r'raise\s+\w+\s*(,)')

Definition at line 101 of file pep8.py.