Do not enforce whitespaces around ** operator; issue #292
[third_party/pep8] / pep8.py
1 #!/usr/bin/env python
2 # pep8.py - Check Python source code formatting, according to PEP 8
3 # Copyright (C) 2006-2009 Johann C. Rocholl <johann@rocholl.net>
4 # Copyright (C) 2009-2014 Florent Xicluna <florent.xicluna@gmail.com>
5 # Copyright (C) 2014 Ian Lee <ianlee1521@gmail.com>
6 #
7 # Permission is hereby granted, free of charge, to any person
8 # obtaining a copy of this software and associated documentation files
9 # (the "Software"), to deal in the Software without restriction,
10 # including without limitation the rights to use, copy, modify, merge,
11 # publish, distribute, sublicense, and/or sell copies of the Software,
12 # and to permit persons to whom the Software is furnished to do so,
13 # subject to the following conditions:
14 #
15 # The above copyright notice and this permission notice shall be
16 # included in all copies or substantial portions of the Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
22 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
23 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 # SOFTWARE.
26
27 r"""
28 Check Python source code formatting, according to PEP 8.
29
30 For usage and a list of options, try this:
31 $ python pep8.py -h
32
33 This program and its regression test suite live here:
34 http://github.com/jcrocholl/pep8
35
36 Groups of errors and warnings:
37 E errors
38 W warnings
39 100 indentation
40 200 whitespace
41 300 blank lines
42 400 imports
43 500 line length
44 600 deprecation
45 700 statements
46 900 syntax error
47 """
48 from __future__ import with_statement
49
50 __version__ = '1.6.0a0'
51
52 import os
53 import sys
54 import re
55 import time
56 import inspect
57 import keyword
58 import tokenize
59 from optparse import OptionParser
60 from fnmatch import fnmatch
61 try:
62     from configparser import RawConfigParser
63     from io import TextIOWrapper
64 except ImportError:
65     from ConfigParser import RawConfigParser
66
67 DEFAULT_EXCLUDE = '.svn,CVS,.bzr,.hg,.git,__pycache__,.tox'
68 DEFAULT_IGNORE = 'E123,E226,E24,E704'
69 try:
70     if sys.platform == 'win32':
71         DEFAULT_CONFIG = os.path.expanduser(r'~\.pep8')
72     else:
73         DEFAULT_CONFIG = os.path.join(os.getenv('XDG_CONFIG_HOME') or
74                                       os.path.expanduser('~/.config'), 'pep8')
75 except ImportError:
76     DEFAULT_CONFIG = None
77
78 PROJECT_CONFIG = ('setup.cfg', 'tox.ini', '.pep8')
79 TESTSUITE_PATH = os.path.join(os.path.dirname(__file__), 'testsuite')
80 MAX_LINE_LENGTH = 79
81 REPORT_FORMAT = {
82     'default': '%(path)s:%(row)d:%(col)d: %(code)s %(text)s',
83     'pylint': '%(path)s:%(row)d: [%(code)s] %(text)s',
84 }
85
86 PyCF_ONLY_AST = 1024
87 SINGLETONS = frozenset(['False', 'None', 'True'])
88 KEYWORDS = frozenset(keyword.kwlist + ['print']) - SINGLETONS
89 UNARY_OPERATORS = frozenset(['>>', '**', '*', '+', '-'])
90 ARITHMETIC_OP = frozenset(['**', '*', '/', '//', '+', '-'])
91 WS_OPTIONAL_OPERATORS = ARITHMETIC_OP.union(['^', '&', '|', '<<', '>>', '%'])
92 WS_NEEDED_OPERATORS = frozenset([
93     '**=', '*=', '/=', '//=', '+=', '-=', '!=', '<>', '<', '>',
94     '%=', '^=', '&=', '|=', '==', '<=', '>=', '<<=', '>>=', '='])
95 WHITESPACE = frozenset(' \t')
96 NEWLINE = frozenset([tokenize.NL, tokenize.NEWLINE])
97 SKIP_TOKENS = NEWLINE.union([tokenize.INDENT, tokenize.DEDENT])
98 # ERRORTOKEN is triggered by backticks in Python 3
99 SKIP_COMMENTS = SKIP_TOKENS.union([tokenize.COMMENT, tokenize.ERRORTOKEN])
100 BENCHMARK_KEYS = ['directories', 'files', 'logical lines', 'physical lines']
101
102 INDENT_REGEX = re.compile(r'([ \t]*)')
103 RAISE_COMMA_REGEX = re.compile(r'raise\s+\w+\s*,')
104 RERAISE_COMMA_REGEX = re.compile(r'raise\s+\w+\s*,.*,\s*\w+\s*$')
105 ERRORCODE_REGEX = re.compile(r'\b[A-Z]\d{3}\b')
106 DOCSTRING_REGEX = re.compile(r'u?r?["\']')
107 EXTRANEOUS_WHITESPACE_REGEX = re.compile(r'[[({] | []}),;:]')
108 WHITESPACE_AFTER_COMMA_REGEX = re.compile(r'[,;:]\s*(?:  |\t)')
109 COMPARE_SINGLETON_REGEX = re.compile(r'(?P<op>[=!]=)\s*'
110                                      r'(?P<singleton>None|False|True)')
111 COMPARE_SINGLETON_REVERSE_REGEX = re.compile(r'(?P<singleton>None|False|True)'
112                                              r'\s*(?P<op>[=!]=)')
113 COMPARE_NEGATIVE_REGEX = re.compile(r'\b(not)\s+[^[({ ]+\s+(in|is)\s')
114 COMPARE_TYPE_REGEX = re.compile(r'(?:[=!]=|is(?:\s+not)?)\s*type(?:s.\w+Type'
115                                 r'|\s*\(\s*([^)]*[^ )])\s*\))')
116 KEYWORD_REGEX = re.compile(r'(\s*)\b(?:%s)\b(\s*)' % r'|'.join(KEYWORDS))
117 OPERATOR_REGEX = re.compile(r'(?:[^,\s])(\s*)(?:[-+*/|!<=>%&^]+)(\s*)')
118 LAMBDA_REGEX = re.compile(r'\blambda\b')
119 HUNK_REGEX = re.compile(r'^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@.*$')
120
121 # Work around Python < 2.6 behaviour, which does not generate NL after
122 # a comment which is on a line by itself.
123 COMMENT_WITH_NL = tokenize.generate_tokens(['#\n'].pop).send(None)[1] == '#\n'
124
125
126 ##############################################################################
127 # Plugins (check functions) for physical lines
128 ##############################################################################
129
130
131 def tabs_or_spaces(physical_line, indent_char):
132     r"""Never mix tabs and spaces.
133
134     The most popular way of indenting Python is with spaces only.  The
135     second-most popular way is with tabs only.  Code indented with a mixture
136     of tabs and spaces should be converted to using spaces exclusively.  When
137     invoking the Python command line interpreter with the -t option, it issues
138     warnings about code that illegally mixes tabs and spaces.  When using -tt
139     these warnings become errors.  These options are highly recommended!
140
141     Okay: if a == 0:\n        a = 1\n        b = 1
142     E101: if a == 0:\n        a = 1\n\tb = 1
143     """
144     indent = INDENT_REGEX.match(physical_line).group(1)
145     for offset, char in enumerate(indent):
146         if char != indent_char:
147             return offset, "E101 indentation contains mixed spaces and tabs"
148
149
150 def tabs_obsolete(physical_line):
151     r"""For new projects, spaces-only are strongly recommended over tabs.
152
153     Okay: if True:\n    return
154     W191: if True:\n\treturn
155     """
156     indent = INDENT_REGEX.match(physical_line).group(1)
157     if '\t' in indent:
158         return indent.index('\t'), "W191 indentation contains tabs"
159
160
161 def trailing_whitespace(physical_line):
162     r"""Trailing whitespace is superfluous.
163
164     The warning returned varies on whether the line itself is blank, for easier
165     filtering for those who want to indent their blank lines.
166
167     Okay: spam(1)\n#
168     W291: spam(1) \n#
169     W293: class Foo(object):\n    \n    bang = 12
170     """
171     physical_line = physical_line.rstrip('\n')    # chr(10), newline
172     physical_line = physical_line.rstrip('\r')    # chr(13), carriage return
173     physical_line = physical_line.rstrip('\x0c')  # chr(12), form feed, ^L
174     stripped = physical_line.rstrip(' \t\v')
175     if physical_line != stripped:
176         if stripped:
177             return len(stripped), "W291 trailing whitespace"
178         else:
179             return 0, "W293 blank line contains whitespace"
180
181
182 def trailing_blank_lines(physical_line, lines, line_number, total_lines):
183     r"""Trailing blank lines are superfluous.
184
185     Okay: spam(1)
186     W391: spam(1)\n
187
188     However the last line should end with a new line (warning W292).
189     """
190     if line_number == total_lines:
191         stripped_last_line = physical_line.rstrip()
192         if not stripped_last_line:
193             return 0, "W391 blank line at end of file"
194         if stripped_last_line == physical_line:
195             return len(physical_line), "W292 no newline at end of file"
196
197
198 def maximum_line_length(physical_line, max_line_length, multiline):
199     r"""Limit all lines to a maximum of 79 characters.
200
201     There are still many devices around that are limited to 80 character
202     lines; plus, limiting windows to 80 characters makes it possible to have
203     several windows side-by-side.  The default wrapping on such devices looks
204     ugly.  Therefore, please limit all lines to a maximum of 79 characters.
205     For flowing long blocks of text (docstrings or comments), limiting the
206     length to 72 characters is recommended.
207
208     Reports error E501.
209     """
210     line = physical_line.rstrip()
211     length = len(line)
212     if length > max_line_length and not noqa(line):
213         # Special case for long URLs in multi-line docstrings or comments,
214         # but still report the error when the 72 first chars are whitespaces.
215         chunks = line.split()
216         if ((len(chunks) == 1 and multiline) or
217             (len(chunks) == 2 and chunks[0] == '#')) and \
218                 len(line) - len(chunks[-1]) < max_line_length - 7:
219             return
220         if hasattr(line, 'decode'):   # Python 2
221             # The line could contain multi-byte characters
222             try:
223                 length = len(line.decode('utf-8'))
224             except UnicodeError:
225                 pass
226         if length > max_line_length:
227             return (max_line_length, "E501 line too long "
228                     "(%d > %d characters)" % (length, max_line_length))
229
230
231 ##############################################################################
232 # Plugins (check functions) for logical lines
233 ##############################################################################
234
235
236 def blank_lines(logical_line, blank_lines, indent_level, line_number,
237                 blank_before, previous_logical, previous_indent_level):
238     r"""Separate top-level function and class definitions with two blank lines.
239
240     Method definitions inside a class are separated by a single blank line.
241
242     Extra blank lines may be used (sparingly) to separate groups of related
243     functions.  Blank lines may be omitted between a bunch of related
244     one-liners (e.g. a set of dummy implementations).
245
246     Use blank lines in functions, sparingly, to indicate logical sections.
247
248     Okay: def a():\n    pass\n\n\ndef b():\n    pass
249     Okay: def a():\n    pass\n\n\n# Foo\n# Bar\n\ndef b():\n    pass
250
251     E301: class Foo:\n    b = 0\n    def bar():\n        pass
252     E302: def a():\n    pass\n\ndef b(n):\n    pass
253     E303: def a():\n    pass\n\n\n\ndef b(n):\n    pass
254     E303: def a():\n\n\n\n    pass
255     E304: @decorator\n\ndef a():\n    pass
256     """
257     if line_number < 3 and not previous_logical:
258         return  # Don't expect blank lines before the first line
259     if previous_logical.startswith('@'):
260         if blank_lines:
261             yield 0, "E304 blank lines found after function decorator"
262     elif blank_lines > 2 or (indent_level and blank_lines == 2):
263         yield 0, "E303 too many blank lines (%d)" % blank_lines
264     elif logical_line.startswith(('def ', 'class ', '@')):
265         if indent_level:
266             if not (blank_before or previous_indent_level < indent_level or
267                     DOCSTRING_REGEX.match(previous_logical)):
268                 yield 0, "E301 expected 1 blank line, found 0"
269         elif blank_before != 2:
270             yield 0, "E302 expected 2 blank lines, found %d" % blank_before
271
272
273 def extraneous_whitespace(logical_line):
274     r"""Avoid extraneous whitespace.
275
276     Avoid extraneous whitespace in these situations:
277     - Immediately inside parentheses, brackets or braces.
278     - Immediately before a comma, semicolon, or colon.
279
280     Okay: spam(ham[1], {eggs: 2})
281     E201: spam( ham[1], {eggs: 2})
282     E201: spam(ham[ 1], {eggs: 2})
283     E201: spam(ham[1], { eggs: 2})
284     E202: spam(ham[1], {eggs: 2} )
285     E202: spam(ham[1 ], {eggs: 2})
286     E202: spam(ham[1], {eggs: 2 })
287
288     E203: if x == 4: print x, y; x, y = y , x
289     E203: if x == 4: print x, y ; x, y = y, x
290     E203: if x == 4 : print x, y; x, y = y, x
291     """
292     line = logical_line
293     for match in EXTRANEOUS_WHITESPACE_REGEX.finditer(line):
294         text = match.group()
295         char = text.strip()
296         found = match.start()
297         if text == char + ' ':
298             # assert char in '([{'
299             yield found + 1, "E201 whitespace after '%s'" % char
300         elif line[found - 1] != ',':
301             code = ('E202' if char in '}])' else 'E203')  # if char in ',;:'
302             yield found, "%s whitespace before '%s'" % (code, char)
303
304
305 def whitespace_around_keywords(logical_line):
306     r"""Avoid extraneous whitespace around keywords.
307
308     Okay: True and False
309     E271: True and  False
310     E272: True  and False
311     E273: True and\tFalse
312     E274: True\tand False
313     """
314     for match in KEYWORD_REGEX.finditer(logical_line):
315         before, after = match.groups()
316
317         if '\t' in before:
318             yield match.start(1), "E274 tab before keyword"
319         elif len(before) > 1:
320             yield match.start(1), "E272 multiple spaces before keyword"
321
322         if '\t' in after:
323             yield match.start(2), "E273 tab after keyword"
324         elif len(after) > 1:
325             yield match.start(2), "E271 multiple spaces after keyword"
326
327
328 def missing_whitespace(logical_line):
329     r"""Each comma, semicolon or colon should be followed by whitespace.
330
331     Okay: [a, b]
332     Okay: (3,)
333     Okay: a[1:4]
334     Okay: a[:4]
335     Okay: a[1:]
336     Okay: a[1:4:2]
337     E231: ['a','b']
338     E231: foo(bar,baz)
339     E231: [{'a':'b'}]
340     """
341     line = logical_line
342     for index in range(len(line) - 1):
343         char = line[index]
344         if char in ',;:' and line[index + 1] not in WHITESPACE:
345             before = line[:index]
346             if char == ':' and before.count('[') > before.count(']') and \
347                     before.rfind('{') < before.rfind('['):
348                 continue  # Slice syntax, no space required
349             if char == ',' and line[index + 1] == ')':
350                 continue  # Allow tuple with only one element: (3,)
351             yield index, "E231 missing whitespace after '%s'" % char
352
353
354 def indentation(logical_line, previous_logical, indent_char,
355                 indent_level, previous_indent_level):
356     r"""Use 4 spaces per indentation level.
357
358     For really old code that you don't want to mess up, you can continue to
359     use 8-space tabs.
360
361     Okay: a = 1
362     Okay: if a == 0:\n    a = 1
363     E111:   a = 1
364     E114:   # a = 1
365
366     Okay: for item in items:\n    pass
367     E112: for item in items:\npass
368     E115: for item in items:\n# Hi\n    pass
369
370     Okay: a = 1\nb = 2
371     E113: a = 1\n    b = 2
372     E116: a = 1\n    # b = 2
373     """
374     c = 0 if logical_line else 3
375     tmpl = "E11%d %s" if logical_line else "E11%d %s (comment)"
376     if indent_level % 4:
377         yield 0, tmpl % (1 + c, "indentation is not a multiple of four")
378     indent_expect = previous_logical.endswith(':')
379     if indent_expect and indent_level <= previous_indent_level:
380         yield 0, tmpl % (2 + c, "expected an indented block")
381     elif not indent_expect and indent_level > previous_indent_level:
382         yield 0, tmpl % (3 + c, "unexpected indentation")
383
384
385 def continued_indentation(logical_line, tokens, indent_level, hang_closing,
386                           indent_char, noqa, verbose):
387     r"""Continuation lines indentation.
388
389     Continuation lines should align wrapped elements either vertically
390     using Python's implicit line joining inside parentheses, brackets
391     and braces, or using a hanging indent.
392
393     When using a hanging indent these considerations should be applied:
394     - there should be no arguments on the first line, and
395     - further indentation should be used to clearly distinguish itself as a
396       continuation line.
397
398     Okay: a = (\n)
399     E123: a = (\n    )
400
401     Okay: a = (\n    42)
402     E121: a = (\n   42)
403     E122: a = (\n42)
404     E123: a = (\n    42\n    )
405     E124: a = (24,\n     42\n)
406     E125: if (\n    b):\n    pass
407     E126: a = (\n        42)
408     E127: a = (24,\n      42)
409     E128: a = (24,\n    42)
410     E129: if (a or\n    b):\n    pass
411     E131: a = (\n    42\n 24)
412     """
413     first_row = tokens[0][2][0]
414     nrows = 1 + tokens[-1][2][0] - first_row
415     if noqa or nrows == 1:
416         return
417
418     # indent_next tells us whether the next block is indented; assuming
419     # that it is indented by 4 spaces, then we should not allow 4-space
420     # indents on the final continuation line; in turn, some other
421     # indents are allowed to have an extra 4 spaces.
422     indent_next = logical_line.endswith(':')
423
424     row = depth = 0
425     valid_hangs = (4,) if indent_char != '\t' else (4, 8)
426     # remember how many brackets were opened on each line
427     parens = [0] * nrows
428     # relative indents of physical lines
429     rel_indent = [0] * nrows
430     # for each depth, collect a list of opening rows
431     open_rows = [[0]]
432     # for each depth, memorize the hanging indentation
433     hangs = [None]
434     # visual indents
435     indent_chances = {}
436     last_indent = tokens[0][2]
437     visual_indent = None
438     # for each depth, memorize the visual indent column
439     indent = [last_indent[1]]
440     if verbose >= 3:
441         print(">>> " + tokens[0][4].rstrip())
442
443     for token_type, text, start, end, line in tokens:
444
445         newline = row < start[0] - first_row
446         if newline:
447             row = start[0] - first_row
448             newline = not last_token_multiline and token_type not in NEWLINE
449
450         if newline:
451             # this is the beginning of a continuation line.
452             last_indent = start
453             if verbose >= 3:
454                 print("... " + line.rstrip())
455
456             # record the initial indent.
457             rel_indent[row] = expand_indent(line) - indent_level
458
459             # identify closing bracket
460             close_bracket = (token_type == tokenize.OP and text in ']})')
461
462             # is the indent relative to an opening bracket line?
463             for open_row in reversed(open_rows[depth]):
464                 hang = rel_indent[row] - rel_indent[open_row]
465                 hanging_indent = hang in valid_hangs
466                 if hanging_indent:
467                     break
468             if hangs[depth]:
469                 hanging_indent = (hang == hangs[depth])
470             # is there any chance of visual indent?
471             visual_indent = (not close_bracket and hang > 0 and
472                              indent_chances.get(start[1]))
473
474             if close_bracket and indent[depth]:
475                 # closing bracket for visual indent
476                 if start[1] != indent[depth]:
477                     yield (start, "E124 closing bracket does not match "
478                            "visual indentation")
479             elif close_bracket and not hang:
480                 # closing bracket matches indentation of opening bracket's line
481                 if hang_closing:
482                     yield start, "E133 closing bracket is missing indentation"
483             elif indent[depth] and start[1] < indent[depth]:
484                 if visual_indent is not True:
485                     # visual indent is broken
486                     yield (start, "E128 continuation line "
487                            "under-indented for visual indent")
488             elif hanging_indent or (indent_next and rel_indent[row] == 8):
489                 # hanging indent is verified
490                 if close_bracket and not hang_closing:
491                     yield (start, "E123 closing bracket does not match "
492                            "indentation of opening bracket's line")
493                 hangs[depth] = hang
494             elif visual_indent is True:
495                 # visual indent is verified
496                 indent[depth] = start[1]
497             elif visual_indent in (text, str):
498                 # ignore token lined up with matching one from a previous line
499                 pass
500             else:
501                 # indent is broken
502                 if hang <= 0:
503                     error = "E122", "missing indentation or outdented"
504                 elif indent[depth]:
505                     error = "E127", "over-indented for visual indent"
506                 elif not close_bracket and hangs[depth]:
507                     error = "E131", "unaligned for hanging indent"
508                 else:
509                     hangs[depth] = hang
510                     if hang > 4:
511                         error = "E126", "over-indented for hanging indent"
512                     else:
513                         error = "E121", "under-indented for hanging indent"
514                 yield start, "%s continuation line %s" % error
515
516         # look for visual indenting
517         if (parens[row] and token_type not in (tokenize.NL, tokenize.COMMENT)
518                 and not indent[depth]):
519             indent[depth] = start[1]
520             indent_chances[start[1]] = True
521             if verbose >= 4:
522                 print("bracket depth %s indent to %s" % (depth, start[1]))
523         # deal with implicit string concatenation
524         elif (token_type in (tokenize.STRING, tokenize.COMMENT) or
525               text in ('u', 'ur', 'b', 'br')):
526             indent_chances[start[1]] = str
527         # special case for the "if" statement because len("if (") == 4
528         elif not indent_chances and not row and not depth and text == 'if':
529             indent_chances[end[1] + 1] = True
530         elif text == ':' and line[end[1]:].isspace():
531             open_rows[depth].append(row)
532
533         # keep track of bracket depth
534         if token_type == tokenize.OP:
535             if text in '([{':
536                 depth += 1
537                 indent.append(0)
538                 hangs.append(None)
539                 if len(open_rows) == depth:
540                     open_rows.append([])
541                 open_rows[depth].append(row)
542                 parens[row] += 1
543                 if verbose >= 4:
544                     print("bracket depth %s seen, col %s, visual min = %s" %
545                           (depth, start[1], indent[depth]))
546             elif text in ')]}' and depth > 0:
547                 # parent indents should not be more than this one
548                 prev_indent = indent.pop() or last_indent[1]
549                 hangs.pop()
550                 for d in range(depth):
551                     if indent[d] > prev_indent:
552                         indent[d] = 0
553                 for ind in list(indent_chances):
554                     if ind >= prev_indent:
555                         del indent_chances[ind]
556                 del open_rows[depth + 1:]
557                 depth -= 1
558                 if depth:
559                     indent_chances[indent[depth]] = True
560                 for idx in range(row, -1, -1):
561                     if parens[idx]:
562                         parens[idx] -= 1
563                         break
564             assert len(indent) == depth + 1
565             if start[1] not in indent_chances:
566                 # allow to line up tokens
567                 indent_chances[start[1]] = text
568
569         last_token_multiline = (start[0] != end[0])
570         if last_token_multiline:
571             rel_indent[end[0] - first_row] = rel_indent[row]
572
573     if indent_next and expand_indent(line) == indent_level + 4:
574         pos = (start[0], indent[0] + 4)
575         if visual_indent:
576             code = "E129 visually indented line"
577         else:
578             code = "E125 continuation line"
579         yield pos, "%s with same indent as next logical line" % code
580
581
582 def whitespace_before_parameters(logical_line, tokens):
583     r"""Avoid extraneous whitespace.
584
585     Avoid extraneous whitespace in the following situations:
586     - before the open parenthesis that starts the argument list of a
587       function call.
588     - before the open parenthesis that starts an indexing or slicing.
589
590     Okay: spam(1)
591     E211: spam (1)
592
593     Okay: dict['key'] = list[index]
594     E211: dict ['key'] = list[index]
595     E211: dict['key'] = list [index]
596     """
597     prev_type, prev_text, __, prev_end, __ = tokens[0]
598     for index in range(1, len(tokens)):
599         token_type, text, start, end, __ = tokens[index]
600         if (token_type == tokenize.OP and
601             text in '([' and
602             start != prev_end and
603             (prev_type == tokenize.NAME or prev_text in '}])') and
604             # Syntax "class A (B):" is allowed, but avoid it
605             (index < 2 or tokens[index - 2][1] != 'class') and
606                 # Allow "return (a.foo for a in range(5))"
607                 not keyword.iskeyword(prev_text)):
608             yield prev_end, "E211 whitespace before '%s'" % text
609         prev_type = token_type
610         prev_text = text
611         prev_end = end
612
613
614 def whitespace_around_operator(logical_line):
615     r"""Avoid extraneous whitespace around an operator.
616
617     Okay: a = 12 + 3
618     E221: a = 4  + 5
619     E222: a = 4 +  5
620     E223: a = 4\t+ 5
621     E224: a = 4 +\t5
622     """
623     for match in OPERATOR_REGEX.finditer(logical_line):
624         before, after = match.groups()
625
626         if '\t' in before:
627             yield match.start(1), "E223 tab before operator"
628         elif len(before) > 1:
629             yield match.start(1), "E221 multiple spaces before operator"
630
631         if '\t' in after:
632             yield match.start(2), "E224 tab after operator"
633         elif len(after) > 1:
634             yield match.start(2), "E222 multiple spaces after operator"
635
636
637 def missing_whitespace_around_operator(logical_line, tokens):
638     r"""Surround operators with a single space on either side.
639
640     - Always surround these binary operators with a single space on
641       either side: assignment (=), augmented assignment (+=, -= etc.),
642       comparisons (==, <, >, !=, <=, >=, in, not in, is, is not),
643       Booleans (and, or, not).
644
645     - If operators with different priorities are used, consider adding
646       whitespace around the operators with the lowest priorities.
647
648     Okay: i = i + 1
649     Okay: submitted += 1
650     Okay: x = x * 2 - 1
651     Okay: hypot2 = x * x + y * y
652     Okay: c = (a + b) * (a - b)
653     Okay: foo(bar, key='word', *args, **kwargs)
654     Okay: alpha[:-i]
655
656     E225: i=i+1
657     E225: submitted +=1
658     E225: x = x /2 - 1
659     E225: z = x **y
660     E226: c = (a+b) * (a-b)
661     E226: hypot2 = x*x + y*y
662     E227: c = a|b
663     E228: msg = fmt%(errno, errmsg)
664     """
665     parens = 0
666     need_space = False
667     prev_type = tokenize.OP
668     prev_text = prev_end = None
669     for token_type, text, start, end, line in tokens:
670         if token_type in SKIP_COMMENTS:
671             continue
672         if text in ('(', 'lambda'):
673             parens += 1
674         elif text == ')':
675             parens -= 1
676         if need_space:
677             if start != prev_end:
678                 # Found a (probably) needed space
679                 if need_space is not True and not need_space[1]:
680                     yield (need_space[0],
681                            "E225 missing whitespace around operator")
682                 need_space = False
683             elif text == '>' and prev_text in ('<', '-'):
684                 # Tolerate the "<>" operator, even if running Python 3
685                 # Deal with Python 3's annotated return value "->"
686                 pass
687             else:
688                 if need_space is True or need_space[1]:
689                     # A needed trailing space was not found
690                     yield prev_end, "E225 missing whitespace around operator"
691                 elif prev_text != '**':
692                     code, optype = 'E226', 'arithmetic'
693                     if prev_text == '%':
694                         code, optype = 'E228', 'modulo'
695                     elif prev_text not in ARITHMETIC_OP:
696                         code, optype = 'E227', 'bitwise or shift'
697                     yield (need_space[0], "%s missing whitespace "
698                            "around %s operator" % (code, optype))
699                 need_space = False
700         elif token_type == tokenize.OP and prev_end is not None:
701             if text == '=' and parens:
702                 # Allow keyword args or defaults: foo(bar=None).
703                 pass
704             elif text in WS_NEEDED_OPERATORS:
705                 need_space = True
706             elif text in UNARY_OPERATORS:
707                 # Check if the operator is being used as a binary operator
708                 # Allow unary operators: -123, -x, +1.
709                 # Allow argument unpacking: foo(*args, **kwargs).
710                 if (prev_text in '}])' if prev_type == tokenize.OP
711                         else prev_text not in KEYWORDS):
712                     need_space = None
713             elif text in WS_OPTIONAL_OPERATORS:
714                 need_space = None
715
716             if need_space is None:
717                 # Surrounding space is optional, but ensure that
718                 # trailing space matches opening space
719                 need_space = (prev_end, start != prev_end)
720             elif need_space and start == prev_end:
721                 # A needed opening space was not found
722                 yield prev_end, "E225 missing whitespace around operator"
723                 need_space = False
724         prev_type = token_type
725         prev_text = text
726         prev_end = end
727
728
729 def whitespace_around_comma(logical_line):
730     r"""Avoid extraneous whitespace after a comma or a colon.
731
732     Note: these checks are disabled by default
733
734     Okay: a = (1, 2)
735     E241: a = (1,  2)
736     E242: a = (1,\t2)
737     """
738     line = logical_line
739     for m in WHITESPACE_AFTER_COMMA_REGEX.finditer(line):
740         found = m.start() + 1
741         if '\t' in m.group():
742             yield found, "E242 tab after '%s'" % m.group()[0]
743         else:
744             yield found, "E241 multiple spaces after '%s'" % m.group()[0]
745
746
747 def whitespace_around_named_parameter_equals(logical_line, tokens):
748     r"""Don't use spaces around the '=' sign in function arguments.
749
750     Don't use spaces around the '=' sign when used to indicate a
751     keyword argument or a default parameter value.
752
753     Okay: def complex(real, imag=0.0):
754     Okay: return magic(r=real, i=imag)
755     Okay: boolean(a == b)
756     Okay: boolean(a != b)
757     Okay: boolean(a <= b)
758     Okay: boolean(a >= b)
759
760     E251: def complex(real, imag = 0.0):
761     E251: return magic(r = real, i = imag)
762     """
763     parens = 0
764     no_space = False
765     prev_end = None
766     message = "E251 unexpected spaces around keyword / parameter equals"
767     for token_type, text, start, end, line in tokens:
768         if token_type == tokenize.NL:
769             continue
770         if no_space:
771             no_space = False
772             if start != prev_end:
773                 yield (prev_end, message)
774         elif token_type == tokenize.OP:
775             if text == '(':
776                 parens += 1
777             elif text == ')':
778                 parens -= 1
779             elif parens and text == '=':
780                 no_space = True
781                 if start != prev_end:
782                     yield (prev_end, message)
783         prev_end = end
784
785
786 def whitespace_before_comment(logical_line, tokens):
787     r"""Separate inline comments by at least two spaces.
788
789     An inline comment is a comment on the same line as a statement.  Inline
790     comments should be separated by at least two spaces from the statement.
791     They should start with a # and a single space.
792
793     Each line of a block comment starts with a # and a single space
794     (unless it is indented text inside the comment).
795
796     Okay: x = x + 1  # Increment x
797     Okay: x = x + 1    # Increment x
798     Okay: # Block comment
799     E261: x = x + 1 # Increment x
800     E262: x = x + 1  #Increment x
801     E262: x = x + 1  #  Increment x
802     E265: #Block comment
803     E266: ### Block comment
804     """
805     prev_end = (0, 0)
806     for token_type, text, start, end, line in tokens:
807         if token_type == tokenize.COMMENT:
808             inline_comment = line[:start[1]].strip()
809             if inline_comment:
810                 if prev_end[0] == start[0] and start[1] < prev_end[1] + 2:
811                     yield (prev_end,
812                            "E261 at least two spaces before inline comment")
813             symbol, sp, comment = text.partition(' ')
814             bad_prefix = symbol not in '#:' and (symbol.lstrip('#')[:1] or '#')
815             if inline_comment:
816                 if bad_prefix or comment[:1] in WHITESPACE:
817                     yield start, "E262 inline comment should start with '# '"
818             elif bad_prefix and (bad_prefix != '!' or start[0] > 1):
819                 if bad_prefix != '#':
820                     yield start, "E265 block comment should start with '# '"
821                 elif comment:
822                     yield start, "E266 too many leading '#' for block comment"
823         elif token_type != tokenize.NL:
824             prev_end = end
825
826
827 def imports_on_separate_lines(logical_line):
828     r"""Imports should usually be on separate lines.
829
830     Okay: import os\nimport sys
831     E401: import sys, os
832
833     Okay: from subprocess import Popen, PIPE
834     Okay: from myclas import MyClass
835     Okay: from foo.bar.yourclass import YourClass
836     Okay: import myclass
837     Okay: import foo.bar.yourclass
838     """
839     line = logical_line
840     if line.startswith('import '):
841         found = line.find(',')
842         if -1 < found and ';' not in line[:found]:
843             yield found, "E401 multiple imports on one line"
844
845
846 def module_imports_on_top_of_file(
847         logical_line, indent_level, checker_state, noqa):
848     r"""Imports are always put at the top of the file, just after any module
849     comments and docstrings, and before module globals and constants.
850
851     Okay: import os
852     Okay: # this is a comment\nimport os
853     Okay: '''this is a module docstring'''\nimport os
854     Okay: r'''this is a module docstring'''\nimport os
855     Okay: __version__ = "123"\nimport os
856     E402: a=1\nimport os
857     E402: 'One string'\n"Two string"\nimport os
858     E402: a=1\nfrom sys import x
859
860     Okay: if x:\n    import os
861     """
862     def is_string_literal(line):
863         if line[0] in 'uUbB':
864             line = line[1:]
865         if line and line[0] in 'rR':
866             line = line[1:]
867         return line and (line[0] == '"' or line[0] == "'")
868
869     if indent_level:  # Allow imports in conditional statements or functions
870         return
871     if not logical_line:  # Allow empty lines or comments
872         return
873     if noqa:
874         return
875     line = logical_line
876     if line.startswith('import ') or line.startswith('from '):
877         if checker_state.get('seen_non_imports', False):
878             yield 0, "E402 import not at top of file"
879     elif line.startswith('__version__ '):
880         # These lines should be included after the module's docstring, before
881         # any other code, separated by a blank line above and below.
882         return
883     elif is_string_literal(line):
884         # The first literal is a docstring, allow it. Otherwise, report error.
885         if checker_state.get('seen_docstring', False):
886             checker_state['seen_non_imports'] = True
887         else:
888             checker_state['seen_docstring'] = True
889     else:
890         checker_state['seen_non_imports'] = True
891
892
893 def compound_statements(logical_line):
894     r"""Compound statements (on the same line) are generally discouraged.
895
896     While sometimes it's okay to put an if/for/while with a small body
897     on the same line, never do this for multi-clause statements.
898     Also avoid folding such long lines!
899
900     Always use a def statement instead of an assignment statement that
901     binds a lambda expression directly to a name.
902
903     Okay: if foo == 'blah':\n    do_blah_thing()
904     Okay: do_one()
905     Okay: do_two()
906     Okay: do_three()
907
908     E701: if foo == 'blah': do_blah_thing()
909     E701: for x in lst: total += x
910     E701: while t < 10: t = delay()
911     E701: if foo == 'blah': do_blah_thing()
912     E701: else: do_non_blah_thing()
913     E701: try: something()
914     E701: finally: cleanup()
915     E701: if foo == 'blah': one(); two(); three()
916     E702: do_one(); do_two(); do_three()
917     E703: do_four();  # useless semicolon
918     E704: def f(x): return 2*x
919     E731: f = lambda x: 2*x
920     """
921     line = logical_line
922     last_char = len(line) - 1
923     found = line.find(':')
924     while -1 < found < last_char:
925         before = line[:found]
926         if ((before.count('{') <= before.count('}') and   # {'a': 1} (dict)
927              before.count('[') <= before.count(']') and   # [1:2] (slice)
928              before.count('(') <= before.count(')'))):    # (annotation)
929             lambda_kw = LAMBDA_REGEX.search(before)
930             if lambda_kw:
931                 before = line[:lambda_kw.start()].rstrip()
932                 if before[-1:] == '=' and isidentifier(before[:-1].strip()):
933                     yield 0, ("E731 do not assign a lambda expression, use a "
934                               "def")
935                 break
936             if before.startswith('def '):
937                 yield 0, "E704 multiple statements on one line (def)"
938             else:
939                 yield found, "E701 multiple statements on one line (colon)"
940         found = line.find(':', found + 1)
941     found = line.find(';')
942     while -1 < found:
943         if found < last_char:
944             yield found, "E702 multiple statements on one line (semicolon)"
945         else:
946             yield found, "E703 statement ends with a semicolon"
947         found = line.find(';', found + 1)
948
949
950 def explicit_line_join(logical_line, tokens):
951     r"""Avoid explicit line join between brackets.
952
953     The preferred way of wrapping long lines is by using Python's implied line
954     continuation inside parentheses, brackets and braces.  Long lines can be
955     broken over multiple lines by wrapping expressions in parentheses.  These
956     should be used in preference to using a backslash for line continuation.
957
958     E502: aaa = [123, \\n       123]
959     E502: aaa = ("bbb " \\n       "ccc")
960
961     Okay: aaa = [123,\n       123]
962     Okay: aaa = ("bbb "\n       "ccc")
963     Okay: aaa = "bbb " \\n    "ccc"
964     """
965     prev_start = prev_end = parens = 0
966     for token_type, text, start, end, line in tokens:
967         if start[0] != prev_start and parens and backslash:
968             yield backslash, "E502 the backslash is redundant between brackets"
969         if end[0] != prev_end:
970             if line.rstrip('\r\n').endswith('\\'):
971                 backslash = (end[0], len(line.splitlines()[-1]) - 1)
972             else:
973                 backslash = None
974             prev_start = prev_end = end[0]
975         else:
976             prev_start = start[0]
977         if token_type == tokenize.OP:
978             if text in '([{':
979                 parens += 1
980             elif text in ')]}':
981                 parens -= 1
982
983
984 def comparison_to_singleton(logical_line, noqa):
985     r"""Comparison to singletons should use "is" or "is not".
986
987     Comparisons to singletons like None should always be done
988     with "is" or "is not", never the equality operators.
989
990     Okay: if arg is not None:
991     E711: if arg != None:
992     E711: if None == arg:
993     E712: if arg == True:
994     E712: if False == arg:
995
996     Also, beware of writing if x when you really mean if x is not None --
997     e.g. when testing whether a variable or argument that defaults to None was
998     set to some other value.  The other value might have a type (such as a
999     container) that could be false in a boolean context!
1000     """
1001
1002     match = not noqa and (COMPARE_SINGLETON_REGEX.search(logical_line) or
1003                           COMPARE_SINGLETON_REVERSE_REGEX.search(logical_line))
1004     if match:
1005         singleton = match.group('singleton')
1006         same = (match.group('op') == '==')
1007
1008         msg = "'if cond is %s:'" % (('' if same else 'not ') + singleton)
1009         if singleton in ('None',):
1010             code = 'E711'
1011         else:
1012             code = 'E712'
1013             nonzero = ((singleton == 'True' and same) or
1014                        (singleton == 'False' and not same))
1015             msg += " or 'if %scond:'" % ('' if nonzero else 'not ')
1016         yield match.start(1), ("%s comparison to %s should be %s" %
1017                                (code, singleton, msg))
1018
1019
1020 def comparison_negative(logical_line):
1021     r"""Negative comparison should be done using "not in" and "is not".
1022
1023     Okay: if x not in y:\n    pass
1024     Okay: assert (X in Y or X is Z)
1025     Okay: if not (X in Y):\n    pass
1026     Okay: zz = x is not y
1027     E713: Z = not X in Y
1028     E713: if not X.B in Y:\n    pass
1029     E714: if not X is Y:\n    pass
1030     E714: Z = not X.B is Y
1031     """
1032     match = COMPARE_NEGATIVE_REGEX.search(logical_line)
1033     if match:
1034         pos = match.start(1)
1035         if match.group(2) == 'in':
1036             yield pos, "E713 test for membership should be 'not in'"
1037         else:
1038             yield pos, "E714 test for object identity should be 'is not'"
1039
1040
1041 def comparison_type(logical_line):
1042     r"""Object type comparisons should always use isinstance().
1043
1044     Do not compare types directly.
1045
1046     Okay: if isinstance(obj, int):
1047     E721: if type(obj) is type(1):
1048
1049     When checking if an object is a string, keep in mind that it might be a
1050     unicode string too! In Python 2.3, str and unicode have a common base
1051     class, basestring, so you can do:
1052
1053     Okay: if isinstance(obj, basestring):
1054     Okay: if type(a1) is type(b1):
1055     """
1056     match = COMPARE_TYPE_REGEX.search(logical_line)
1057     if match:
1058         inst = match.group(1)
1059         if inst and isidentifier(inst) and inst not in SINGLETONS:
1060             return  # Allow comparison for types which are not obvious
1061         yield match.start(), "E721 do not compare types, use 'isinstance()'"
1062
1063
1064 def python_3000_has_key(logical_line, noqa):
1065     r"""The {}.has_key() method is removed in Python 3: use the 'in' operator.
1066
1067     Okay: if "alph" in d:\n    print d["alph"]
1068     W601: assert d.has_key('alph')
1069     """
1070     pos = logical_line.find('.has_key(')
1071     if pos > -1 and not noqa:
1072         yield pos, "W601 .has_key() is deprecated, use 'in'"
1073
1074
1075 def python_3000_raise_comma(logical_line):
1076     r"""When raising an exception, use "raise ValueError('message')".
1077
1078     The older form is removed in Python 3.
1079
1080     Okay: raise DummyError("Message")
1081     W602: raise DummyError, "Message"
1082     """
1083     match = RAISE_COMMA_REGEX.match(logical_line)
1084     if match and not RERAISE_COMMA_REGEX.match(logical_line):
1085         yield match.end() - 1, "W602 deprecated form of raising exception"
1086
1087
1088 def python_3000_not_equal(logical_line):
1089     r"""New code should always use != instead of <>.
1090
1091     The older syntax is removed in Python 3.
1092
1093     Okay: if a != 'no':
1094     W603: if a <> 'no':
1095     """
1096     pos = logical_line.find('<>')
1097     if pos > -1:
1098         yield pos, "W603 '<>' is deprecated, use '!='"
1099
1100
1101 def python_3000_backticks(logical_line):
1102     r"""Backticks are removed in Python 3: use repr() instead.
1103
1104     Okay: val = repr(1 + 2)
1105     W604: val = `1 + 2`
1106     """
1107     pos = logical_line.find('`')
1108     if pos > -1:
1109         yield pos, "W604 backticks are deprecated, use 'repr()'"
1110
1111
1112 ##############################################################################
1113 # Helper functions
1114 ##############################################################################
1115
1116
1117 if '' == ''.encode():
1118     # Python 2: implicit encoding.
1119     def readlines(filename):
1120         """Read the source code."""
1121         with open(filename, 'rU') as f:
1122             return f.readlines()
1123     isidentifier = re.compile(r'[a-zA-Z_]\w*$').match
1124     stdin_get_value = sys.stdin.read
1125 else:
1126     # Python 3
1127     def readlines(filename):
1128         """Read the source code."""
1129         try:
1130             with open(filename, 'rb') as f:
1131                 (coding, lines) = tokenize.detect_encoding(f.readline)
1132                 f = TextIOWrapper(f, coding, line_buffering=True)
1133                 return [l.decode(coding) for l in lines] + f.readlines()
1134         except (LookupError, SyntaxError, UnicodeError):
1135             # Fall back if file encoding is improperly declared
1136             with open(filename, encoding='latin-1') as f:
1137                 return f.readlines()
1138     isidentifier = str.isidentifier
1139
1140     def stdin_get_value():
1141         return TextIOWrapper(sys.stdin.buffer, errors='ignore').read()
1142 noqa = re.compile(r'# no(?:qa|pep8)\b', re.I).search
1143
1144
1145 def expand_indent(line):
1146     r"""Return the amount of indentation.
1147
1148     Tabs are expanded to the next multiple of 8.
1149
1150     >>> expand_indent('    ')
1151     4
1152     >>> expand_indent('\t')
1153     8
1154     >>> expand_indent('       \t')
1155     8
1156     >>> expand_indent('        \t')
1157     16
1158     """
1159     if '\t' not in line:
1160         return len(line) - len(line.lstrip())
1161     result = 0
1162     for char in line:
1163         if char == '\t':
1164             result = result // 8 * 8 + 8
1165         elif char == ' ':
1166             result += 1
1167         else:
1168             break
1169     return result
1170
1171
1172 def mute_string(text):
1173     """Replace contents with 'xxx' to prevent syntax matching.
1174
1175     >>> mute_string('"abc"')
1176     '"xxx"'
1177     >>> mute_string("'''abc'''")
1178     "'''xxx'''"
1179     >>> mute_string("r'abc'")
1180     "r'xxx'"
1181     """
1182     # String modifiers (e.g. u or r)
1183     start = text.index(text[-1]) + 1
1184     end = len(text) - 1
1185     # Triple quotes
1186     if text[-3:] in ('"""', "'''"):
1187         start += 2
1188         end -= 2
1189     return text[:start] + 'x' * (end - start) + text[end:]
1190
1191
1192 def parse_udiff(diff, patterns=None, parent='.'):
1193     """Return a dictionary of matching lines."""
1194     # For each file of the diff, the entry key is the filename,
1195     # and the value is a set of row numbers to consider.
1196     rv = {}
1197     path = nrows = None
1198     for line in diff.splitlines():
1199         if nrows:
1200             if line[:1] != '-':
1201                 nrows -= 1
1202             continue
1203         if line[:3] == '@@ ':
1204             hunk_match = HUNK_REGEX.match(line)
1205             (row, nrows) = [int(g or '1') for g in hunk_match.groups()]
1206             rv[path].update(range(row, row + nrows))
1207         elif line[:3] == '+++':
1208             path = line[4:].split('\t', 1)[0]
1209             if path[:2] == 'b/':
1210                 path = path[2:]
1211             rv[path] = set()
1212     return dict([(os.path.join(parent, path), rows)
1213                  for (path, rows) in rv.items()
1214                  if rows and filename_match(path, patterns)])
1215
1216
1217 def normalize_paths(value, parent=os.curdir):
1218     """Parse a comma-separated list of paths.
1219
1220     Return a list of absolute paths.
1221     """
1222     if not value:
1223         return []
1224     if isinstance(value, list):
1225         return value
1226     paths = []
1227     for path in value.split(','):
1228         path = path.strip()
1229         if '/' in path:
1230             path = os.path.abspath(os.path.join(parent, path))
1231         paths.append(path.rstrip('/'))
1232     return paths
1233
1234
1235 def filename_match(filename, patterns, default=True):
1236     """Check if patterns contains a pattern that matches filename.
1237
1238     If patterns is unspecified, this always returns True.
1239     """
1240     if not patterns:
1241         return default
1242     return any(fnmatch(filename, pattern) for pattern in patterns)
1243
1244
1245 if COMMENT_WITH_NL:
1246     def _is_eol_token(token):
1247         return (token[0] in NEWLINE or
1248                 (token[0] == tokenize.COMMENT and token[1] == token[4]))
1249 else:
1250     def _is_eol_token(token):
1251         return token[0] in NEWLINE
1252
1253
1254 ##############################################################################
1255 # Framework to run all checks
1256 ##############################################################################
1257
1258
1259 _checks = {'physical_line': {}, 'logical_line': {}, 'tree': {}}
1260
1261
1262 def register_check(check, codes=None):
1263     """Register a new check object."""
1264     def _add_check(check, kind, codes, args):
1265         if check in _checks[kind]:
1266             _checks[kind][check][0].extend(codes or [])
1267         else:
1268             _checks[kind][check] = (codes or [''], args)
1269     if inspect.isfunction(check):
1270         args = inspect.getargspec(check)[0]
1271         if args and args[0] in ('physical_line', 'logical_line'):
1272             if codes is None:
1273                 codes = ERRORCODE_REGEX.findall(check.__doc__ or '')
1274             _add_check(check, args[0], codes, args)
1275     elif inspect.isclass(check):
1276         if inspect.getargspec(check.__init__)[0][:2] == ['self', 'tree']:
1277             _add_check(check, 'tree', codes, None)
1278
1279
1280 def init_checks_registry():
1281     """Register all globally visible functions.
1282
1283     The first argument name is either 'physical_line' or 'logical_line'.
1284     """
1285     mod = inspect.getmodule(register_check)
1286     for (name, function) in inspect.getmembers(mod, inspect.isfunction):
1287         register_check(function)
1288 init_checks_registry()
1289
1290
1291 class Checker(object):
1292     """Load a Python source file, tokenize it, check coding style."""
1293
1294     def __init__(self, filename=None, lines=None,
1295                  options=None, report=None, **kwargs):
1296         if options is None:
1297             options = StyleGuide(kwargs).options
1298         else:
1299             assert not kwargs
1300         self._io_error = None
1301         self._physical_checks = options.physical_checks
1302         self._logical_checks = options.logical_checks
1303         self._ast_checks = options.ast_checks
1304         self.max_line_length = options.max_line_length
1305         self.multiline = False  # in a multiline string?
1306         self.hang_closing = options.hang_closing
1307         self.verbose = options.verbose
1308         self.filename = filename
1309         # Dictionary where a checker can store its custom state.
1310         self._checker_states = {}
1311         if filename is None:
1312             self.filename = 'stdin'
1313             self.lines = lines or []
1314         elif filename == '-':
1315             self.filename = 'stdin'
1316             self.lines = stdin_get_value().splitlines(True)
1317         elif lines is None:
1318             try:
1319                 self.lines = readlines(filename)
1320             except IOError:
1321                 (exc_type, exc) = sys.exc_info()[:2]
1322                 self._io_error = '%s: %s' % (exc_type.__name__, exc)
1323                 self.lines = []
1324         else:
1325             self.lines = lines
1326         if self.lines:
1327             ord0 = ord(self.lines[0][0])
1328             if ord0 in (0xef, 0xfeff):  # Strip the UTF-8 BOM
1329                 if ord0 == 0xfeff:
1330                     self.lines[0] = self.lines[0][1:]
1331                 elif self.lines[0][:3] == '\xef\xbb\xbf':
1332                     self.lines[0] = self.lines[0][3:]
1333         self.report = report or options.report
1334         self.report_error = self.report.error
1335
1336     def report_invalid_syntax(self):
1337         """Check if the syntax is valid."""
1338         (exc_type, exc) = sys.exc_info()[:2]
1339         if len(exc.args) > 1:
1340             offset = exc.args[1]
1341             if len(offset) > 2:
1342                 offset = offset[1:3]
1343         else:
1344             offset = (1, 0)
1345         self.report_error(offset[0], offset[1] or 0,
1346                           'E901 %s: %s' % (exc_type.__name__, exc.args[0]),
1347                           self.report_invalid_syntax)
1348
1349     def readline(self):
1350         """Get the next line from the input buffer."""
1351         if self.line_number >= self.total_lines:
1352             return ''
1353         line = self.lines[self.line_number]
1354         self.line_number += 1
1355         if self.indent_char is None and line[:1] in WHITESPACE:
1356             self.indent_char = line[0]
1357         return line
1358
1359     def run_check(self, check, argument_names):
1360         """Run a check plugin."""
1361         arguments = []
1362         for name in argument_names:
1363             arguments.append(getattr(self, name))
1364         return check(*arguments)
1365
1366     def init_checker_state(self, name, argument_names):
1367         """ Prepares a custom state for the specific checker plugin."""
1368         if 'checker_state' in argument_names:
1369             self.checker_state = self._checker_states.setdefault(name, {})
1370
1371     def check_physical(self, line):
1372         """Run all physical checks on a raw input line."""
1373         self.physical_line = line
1374         for name, check, argument_names in self._physical_checks:
1375             self.init_checker_state(name, argument_names)
1376             result = self.run_check(check, argument_names)
1377             if result is not None:
1378                 (offset, text) = result
1379                 self.report_error(self.line_number, offset, text, check)
1380                 if text[:4] == 'E101':
1381                     self.indent_char = line[0]
1382
1383     def build_tokens_line(self):
1384         """Build a logical line from tokens."""
1385         logical = []
1386         comments = []
1387         length = 0
1388         prev_row = prev_col = mapping = None
1389         for token_type, text, start, end, line in self.tokens:
1390             if token_type in SKIP_TOKENS:
1391                 continue
1392             if not mapping:
1393                 mapping = [(0, start)]
1394             if token_type == tokenize.COMMENT:
1395                 comments.append(text)
1396                 continue
1397             if token_type == tokenize.STRING:
1398                 text = mute_string(text)
1399             if prev_row:
1400                 (start_row, start_col) = start
1401                 if prev_row != start_row:    # different row
1402                     prev_text = self.lines[prev_row - 1][prev_col - 1]
1403                     if prev_text == ',' or (prev_text not in '{[('
1404                                             and text not in '}])'):
1405                         text = ' ' + text
1406                 elif prev_col != start_col:  # different column
1407                     text = line[prev_col:start_col] + text
1408             logical.append(text)
1409             length += len(text)
1410             mapping.append((length, end))
1411             (prev_row, prev_col) = end
1412         self.logical_line = ''.join(logical)
1413         self.noqa = comments and noqa(''.join(comments))
1414         return mapping
1415
1416     def check_logical(self):
1417         """Build a line from tokens and run all logical checks on it."""
1418         self.report.increment_logical_line()
1419         mapping = self.build_tokens_line()
1420
1421         if not mapping:
1422             return
1423
1424         (start_row, start_col) = mapping[0][1]
1425         start_line = self.lines[start_row - 1]
1426         self.indent_level = expand_indent(start_line[:start_col])
1427         if self.blank_before < self.blank_lines:
1428             self.blank_before = self.blank_lines
1429         if self.verbose >= 2:
1430             print(self.logical_line[:80].rstrip())
1431         for name, check, argument_names in self._logical_checks:
1432             if self.verbose >= 4:
1433                 print('   ' + name)
1434             self.init_checker_state(name, argument_names)
1435             for offset, text in self.run_check(check, argument_names) or ():
1436                 if not isinstance(offset, tuple):
1437                     for token_offset, pos in mapping:
1438                         if offset <= token_offset:
1439                             break
1440                     offset = (pos[0], pos[1] + offset - token_offset)
1441                 self.report_error(offset[0], offset[1], text, check)
1442         if self.logical_line:
1443             self.previous_indent_level = self.indent_level
1444             self.previous_logical = self.logical_line
1445         self.blank_lines = 0
1446         self.tokens = []
1447
1448     def check_ast(self):
1449         """Build the file's AST and run all AST checks."""
1450         try:
1451             tree = compile(''.join(self.lines), '', 'exec', PyCF_ONLY_AST)
1452         except (SyntaxError, TypeError):
1453             return self.report_invalid_syntax()
1454         for name, cls, __ in self._ast_checks:
1455             checker = cls(tree, self.filename)
1456             for lineno, offset, text, check in checker.run():
1457                 if not self.lines or not noqa(self.lines[lineno - 1]):
1458                     self.report_error(lineno, offset, text, check)
1459
1460     def generate_tokens(self):
1461         """Tokenize the file, run physical line checks and yield tokens."""
1462         if self._io_error:
1463             self.report_error(1, 0, 'E902 %s' % self._io_error, readlines)
1464         tokengen = tokenize.generate_tokens(self.readline)
1465         try:
1466             for token in tokengen:
1467                 if token[2][0] > self.total_lines:
1468                     return
1469                 self.maybe_check_physical(token)
1470                 yield token
1471         except (SyntaxError, tokenize.TokenError):
1472             self.report_invalid_syntax()
1473
1474     def maybe_check_physical(self, token):
1475         """If appropriate (based on token), check current physical line(s)."""
1476         # Called after every token, but act only on end of line.
1477         if _is_eol_token(token):
1478             # Obviously, a newline token ends a single physical line.
1479             self.check_physical(token[4])
1480         elif token[0] == tokenize.STRING and '\n' in token[1]:
1481             # Less obviously, a string that contains newlines is a
1482             # multiline string, either triple-quoted or with internal
1483             # newlines backslash-escaped. Check every physical line in the
1484             # string *except* for the last one: its newline is outside of
1485             # the multiline string, so we consider it a regular physical
1486             # line, and will check it like any other physical line.
1487             #
1488             # Subtleties:
1489             # - we don't *completely* ignore the last line; if it contains
1490             #   the magical "# noqa" comment, we disable all physical
1491             #   checks for the entire multiline string
1492             # - have to wind self.line_number back because initially it
1493             #   points to the last line of the string, and we want
1494             #   check_physical() to give accurate feedback
1495             if noqa(token[4]):
1496                 return
1497             self.multiline = True
1498             self.line_number = token[2][0]
1499             for line in token[1].split('\n')[:-1]:
1500                 self.check_physical(line + '\n')
1501                 self.line_number += 1
1502             self.multiline = False
1503
1504     def check_all(self, expected=None, line_offset=0):
1505         """Run all checks on the input file."""
1506         self.report.init_file(self.filename, self.lines, expected, line_offset)
1507         self.total_lines = len(self.lines)
1508         if self._ast_checks:
1509             self.check_ast()
1510         self.line_number = 0
1511         self.indent_char = None
1512         self.indent_level = self.previous_indent_level = 0
1513         self.previous_logical = ''
1514         self.tokens = []
1515         self.blank_lines = self.blank_before = 0
1516         parens = 0
1517         for token in self.generate_tokens():
1518             self.tokens.append(token)
1519             token_type, text = token[0:2]
1520             if self.verbose >= 3:
1521                 if token[2][0] == token[3][0]:
1522                     pos = '[%s:%s]' % (token[2][1] or '', token[3][1])
1523                 else:
1524                     pos = 'l.%s' % token[3][0]
1525                 print('l.%s\t%s\t%s\t%r' %
1526                       (token[2][0], pos, tokenize.tok_name[token[0]], text))
1527             if token_type == tokenize.OP:
1528                 if text in '([{':
1529                     parens += 1
1530                 elif text in '}])':
1531                     parens -= 1
1532             elif not parens:
1533                 if token_type in NEWLINE:
1534                     if token_type == tokenize.NEWLINE:
1535                         self.check_logical()
1536                         self.blank_before = 0
1537                     elif len(self.tokens) == 1:
1538                         # The physical line contains only this token.
1539                         self.blank_lines += 1
1540                         del self.tokens[0]
1541                     else:
1542                         self.check_logical()
1543                 elif COMMENT_WITH_NL and token_type == tokenize.COMMENT:
1544                     if len(self.tokens) == 1:
1545                         # The comment also ends a physical line
1546                         token = list(token)
1547                         token[1] = text.rstrip('\r\n')
1548                         token[3] = (token[2][0], token[2][1] + len(token[1]))
1549                         self.tokens = [tuple(token)]
1550                         self.check_logical()
1551         if self.tokens:
1552             self.check_physical(self.lines[-1])
1553             self.check_logical()
1554         return self.report.get_file_results()
1555
1556
1557 class BaseReport(object):
1558     """Collect the results of the checks."""
1559
1560     print_filename = False
1561
1562     def __init__(self, options):
1563         self._benchmark_keys = options.benchmark_keys
1564         self._ignore_code = options.ignore_code
1565         # Results
1566         self.elapsed = 0
1567         self.total_errors = 0
1568         self.counters = dict.fromkeys(self._benchmark_keys, 0)
1569         self.messages = {}
1570
1571     def start(self):
1572         """Start the timer."""
1573         self._start_time = time.time()
1574
1575     def stop(self):
1576         """Stop the timer."""
1577         self.elapsed = time.time() - self._start_time
1578
1579     def init_file(self, filename, lines, expected, line_offset):
1580         """Signal a new file."""
1581         self.filename = filename
1582         self.lines = lines
1583         self.expected = expected or ()
1584         self.line_offset = line_offset
1585         self.file_errors = 0
1586         self.counters['files'] += 1
1587         self.counters['physical lines'] += len(lines)
1588
1589     def increment_logical_line(self):
1590         """Signal a new logical line."""
1591         self.counters['logical lines'] += 1
1592
1593     def error(self, line_number, offset, text, check):
1594         """Report an error, according to options."""
1595         code = text[:4]
1596         if self._ignore_code(code):
1597             return
1598         if code in self.counters:
1599             self.counters[code] += 1
1600         else:
1601             self.counters[code] = 1
1602             self.messages[code] = text[5:]
1603         # Don't care about expected errors or warnings
1604         if code in self.expected:
1605             return
1606         if self.print_filename and not self.file_errors:
1607             print(self.filename)
1608         self.file_errors += 1
1609         self.total_errors += 1
1610         return code
1611
1612     def get_file_results(self):
1613         """Return the count of errors and warnings for this file."""
1614         return self.file_errors
1615
1616     def get_count(self, prefix=''):
1617         """Return the total count of errors and warnings."""
1618         return sum([self.counters[key]
1619                     for key in self.messages if key.startswith(prefix)])
1620
1621     def get_statistics(self, prefix=''):
1622         """Get statistics for message codes that start with the prefix.
1623
1624         prefix='' matches all errors and warnings
1625         prefix='E' matches all errors
1626         prefix='W' matches all warnings
1627         prefix='E4' matches all errors that have to do with imports
1628         """
1629         return ['%-7s %s %s' % (self.counters[key], key, self.messages[key])
1630                 for key in sorted(self.messages) if key.startswith(prefix)]
1631
1632     def print_statistics(self, prefix=''):
1633         """Print overall statistics (number of errors and warnings)."""
1634         for line in self.get_statistics(prefix):
1635             print(line)
1636
1637     def print_benchmark(self):
1638         """Print benchmark numbers."""
1639         print('%-7.2f %s' % (self.elapsed, 'seconds elapsed'))
1640         if self.elapsed:
1641             for key in self._benchmark_keys:
1642                 print('%-7d %s per second (%d total)' %
1643                       (self.counters[key] / self.elapsed, key,
1644                        self.counters[key]))
1645
1646
1647 class FileReport(BaseReport):
1648     """Collect the results of the checks and print only the filenames."""
1649     print_filename = True
1650
1651
1652 class StandardReport(BaseReport):
1653     """Collect and print the results of the checks."""
1654
1655     def __init__(self, options):
1656         super(StandardReport, self).__init__(options)
1657         self._fmt = REPORT_FORMAT.get(options.format.lower(),
1658                                       options.format)
1659         self._repeat = options.repeat
1660         self._show_source = options.show_source
1661         self._show_pep8 = options.show_pep8
1662
1663     def init_file(self, filename, lines, expected, line_offset):
1664         """Signal a new file."""
1665         self._deferred_print = []
1666         return super(StandardReport, self).init_file(
1667             filename, lines, expected, line_offset)
1668
1669     def error(self, line_number, offset, text, check):
1670         """Report an error, according to options."""
1671         code = super(StandardReport, self).error(line_number, offset,
1672                                                  text, check)
1673         if code and (self.counters[code] == 1 or self._repeat):
1674             self._deferred_print.append(
1675                 (line_number, offset, code, text[5:], check.__doc__))
1676         return code
1677
1678     def get_file_results(self):
1679         """Print the result and return the overall count for this file."""
1680         self._deferred_print.sort()
1681         for line_number, offset, code, text, doc in self._deferred_print:
1682             print(self._fmt % {
1683                 'path': self.filename,
1684                 'row': self.line_offset + line_number, 'col': offset + 1,
1685                 'code': code, 'text': text,
1686             })
1687             if self._show_source:
1688                 if line_number > len(self.lines):
1689                     line = ''
1690                 else:
1691                     line = self.lines[line_number - 1]
1692                 print(line.rstrip())
1693                 print(re.sub(r'\S', ' ', line[:offset]) + '^')
1694             if self._show_pep8 and doc:
1695                 print('    ' + doc.strip())
1696         return self.file_errors
1697
1698
1699 class DiffReport(StandardReport):
1700     """Collect and print the results for the changed lines only."""
1701
1702     def __init__(self, options):
1703         super(DiffReport, self).__init__(options)
1704         self._selected = options.selected_lines
1705
1706     def error(self, line_number, offset, text, check):
1707         if line_number not in self._selected[self.filename]:
1708             return
1709         return super(DiffReport, self).error(line_number, offset, text, check)
1710
1711
1712 class StyleGuide(object):
1713     """Initialize a PEP-8 instance with few options."""
1714
1715     def __init__(self, *args, **kwargs):
1716         # build options from the command line
1717         self.checker_class = kwargs.pop('checker_class', Checker)
1718         parse_argv = kwargs.pop('parse_argv', False)
1719         config_file = kwargs.pop('config_file', None)
1720         parser = kwargs.pop('parser', None)
1721         # build options from dict
1722         options_dict = dict(*args, **kwargs)
1723         arglist = None if parse_argv else options_dict.get('paths', None)
1724         options, self.paths = process_options(
1725             arglist, parse_argv, config_file, parser)
1726         if options_dict:
1727             options.__dict__.update(options_dict)
1728             if 'paths' in options_dict:
1729                 self.paths = options_dict['paths']
1730
1731         self.runner = self.input_file
1732         self.options = options
1733
1734         if not options.reporter:
1735             options.reporter = BaseReport if options.quiet else StandardReport
1736
1737         options.select = tuple(options.select or ())
1738         if not (options.select or options.ignore or
1739                 options.testsuite or options.doctest) and DEFAULT_IGNORE:
1740             # The default choice: ignore controversial checks
1741             options.ignore = tuple(DEFAULT_IGNORE.split(','))
1742         else:
1743             # Ignore all checks which are not explicitly selected
1744             options.ignore = ('',) if options.select else tuple(options.ignore)
1745         options.benchmark_keys = BENCHMARK_KEYS[:]
1746         options.ignore_code = self.ignore_code
1747         options.physical_checks = self.get_checks('physical_line')
1748         options.logical_checks = self.get_checks('logical_line')
1749         options.ast_checks = self.get_checks('tree')
1750         self.init_report()
1751
1752     def init_report(self, reporter=None):
1753         """Initialize the report instance."""
1754         self.options.report = (reporter or self.options.reporter)(self.options)
1755         return self.options.report
1756
1757     def check_files(self, paths=None):
1758         """Run all checks on the paths."""
1759         if paths is None:
1760             paths = self.paths
1761         report = self.options.report
1762         runner = self.runner
1763         report.start()
1764         try:
1765             for path in paths:
1766                 if os.path.isdir(path):
1767                     self.input_dir(path)
1768                 elif not self.excluded(path):
1769                     runner(path)
1770         except KeyboardInterrupt:
1771             print('... stopped')
1772         report.stop()
1773         return report
1774
1775     def input_file(self, filename, lines=None, expected=None, line_offset=0):
1776         """Run all checks on a Python source file."""
1777         if self.options.verbose:
1778             print('checking %s' % filename)
1779         fchecker = self.checker_class(
1780             filename, lines=lines, options=self.options)
1781         return fchecker.check_all(expected=expected, line_offset=line_offset)
1782
1783     def input_dir(self, dirname):
1784         """Check all files in this directory and all subdirectories."""
1785         dirname = dirname.rstrip('/')
1786         if self.excluded(dirname):
1787             return 0
1788         counters = self.options.report.counters
1789         verbose = self.options.verbose
1790         filepatterns = self.options.filename
1791         runner = self.runner
1792         for root, dirs, files in os.walk(dirname):
1793             if verbose:
1794                 print('directory ' + root)
1795             counters['directories'] += 1
1796             for subdir in sorted(dirs):
1797                 if self.excluded(subdir, root):
1798                     dirs.remove(subdir)
1799             for filename in sorted(files):
1800                 # contain a pattern that matches?
1801                 if ((filename_match(filename, filepatterns) and
1802                      not self.excluded(filename, root))):
1803                     runner(os.path.join(root, filename))
1804
1805     def excluded(self, filename, parent=None):
1806         """Check if the file should be excluded.
1807
1808         Check if 'options.exclude' contains a pattern that matches filename.
1809         """
1810         if not self.options.exclude:
1811             return False
1812         basename = os.path.basename(filename)
1813         if filename_match(basename, self.options.exclude):
1814             return True
1815         if parent:
1816             filename = os.path.join(parent, filename)
1817         filename = os.path.abspath(filename)
1818         return filename_match(filename, self.options.exclude)
1819
1820     def ignore_code(self, code):
1821         """Check if the error code should be ignored.
1822
1823         If 'options.select' contains a prefix of the error code,
1824         return False.  Else, if 'options.ignore' contains a prefix of
1825         the error code, return True.
1826         """
1827         if len(code) < 4 and any(s.startswith(code)
1828                                  for s in self.options.select):
1829             return False
1830         return (code.startswith(self.options.ignore) and
1831                 not code.startswith(self.options.select))
1832
1833     def get_checks(self, argument_name):
1834         """Get all the checks for this category.
1835
1836         Find all globally visible functions where the first argument name
1837         starts with argument_name and which contain selected tests.
1838         """
1839         checks = []
1840         for check, attrs in _checks[argument_name].items():
1841             (codes, args) = attrs
1842             if any(not (code and self.ignore_code(code)) for code in codes):
1843                 checks.append((check.__name__, check, args))
1844         return sorted(checks)
1845
1846
1847 def get_parser(prog='pep8', version=__version__):
1848     parser = OptionParser(prog=prog, version=version,
1849                           usage="%prog [options] input ...")
1850     parser.config_options = [
1851         'exclude', 'filename', 'select', 'ignore', 'max-line-length',
1852         'hang-closing', 'count', 'format', 'quiet', 'show-pep8',
1853         'show-source', 'statistics', 'verbose']
1854     parser.add_option('-v', '--verbose', default=0, action='count',
1855                       help="print status messages, or debug with -vv")
1856     parser.add_option('-q', '--quiet', default=0, action='count',
1857                       help="report only file names, or nothing with -qq")
1858     parser.add_option('-r', '--repeat', default=True, action='store_true',
1859                       help="(obsolete) show all occurrences of the same error")
1860     parser.add_option('--first', action='store_false', dest='repeat',
1861                       help="show first occurrence of each error")
1862     parser.add_option('--exclude', metavar='patterns', default=DEFAULT_EXCLUDE,
1863                       help="exclude files or directories which match these "
1864                            "comma separated patterns (default: %default)")
1865     parser.add_option('--filename', metavar='patterns', default='*.py',
1866                       help="when parsing directories, only check filenames "
1867                            "matching these comma separated patterns "
1868                            "(default: %default)")
1869     parser.add_option('--select', metavar='errors', default='',
1870                       help="select errors and warnings (e.g. E,W6)")
1871     parser.add_option('--ignore', metavar='errors', default='',
1872                       help="skip errors and warnings (e.g. E4,W)")
1873     parser.add_option('--show-source', action='store_true',
1874                       help="show source code for each error")
1875     parser.add_option('--show-pep8', action='store_true',
1876                       help="show text of PEP 8 for each error "
1877                            "(implies --first)")
1878     parser.add_option('--statistics', action='store_true',
1879                       help="count errors and warnings")
1880     parser.add_option('--count', action='store_true',
1881                       help="print total number of errors and warnings "
1882                            "to standard error and set exit code to 1 if "
1883                            "total is not null")
1884     parser.add_option('--max-line-length', type='int', metavar='n',
1885                       default=MAX_LINE_LENGTH,
1886                       help="set maximum allowed line length "
1887                            "(default: %default)")
1888     parser.add_option('--hang-closing', action='store_true',
1889                       help="hang closing bracket instead of matching "
1890                            "indentation of opening bracket's line")
1891     parser.add_option('--format', metavar='format', default='default',
1892                       help="set the error format [default|pylint|<custom>]")
1893     parser.add_option('--diff', action='store_true',
1894                       help="report only lines changed according to the "
1895                            "unified diff received on STDIN")
1896     group = parser.add_option_group("Testing Options")
1897     if os.path.exists(TESTSUITE_PATH):
1898         group.add_option('--testsuite', metavar='dir',
1899                          help="run regression tests from dir")
1900         group.add_option('--doctest', action='store_true',
1901                          help="run doctest on myself")
1902     group.add_option('--benchmark', action='store_true',
1903                      help="measure processing speed")
1904     return parser
1905
1906
1907 def read_config(options, args, arglist, parser):
1908     """Read both user configuration and local configuration."""
1909     config = RawConfigParser()
1910
1911     user_conf = options.config
1912     if user_conf and os.path.isfile(user_conf):
1913         if options.verbose:
1914             print('user configuration: %s' % user_conf)
1915         config.read(user_conf)
1916
1917     local_dir = os.curdir
1918     parent = tail = args and os.path.abspath(os.path.commonprefix(args))
1919     while tail:
1920         if config.read([os.path.join(parent, fn) for fn in PROJECT_CONFIG]):
1921             local_dir = parent
1922             if options.verbose:
1923                 print('local configuration: in %s' % parent)
1924             break
1925         (parent, tail) = os.path.split(parent)
1926
1927     pep8_section = parser.prog
1928     if config.has_section(pep8_section):
1929         option_list = dict([(o.dest, o.type or o.action)
1930                             for o in parser.option_list])
1931
1932         # First, read the default values
1933         (new_options, __) = parser.parse_args([])
1934
1935         # Second, parse the configuration
1936         for opt in config.options(pep8_section):
1937             if opt.replace('_', '-') not in parser.config_options:
1938                 print("  unknown option '%s' ignored" % opt)
1939                 continue
1940             if options.verbose > 1:
1941                 print("  %s = %s" % (opt, config.get(pep8_section, opt)))
1942             normalized_opt = opt.replace('-', '_')
1943             opt_type = option_list[normalized_opt]
1944             if opt_type in ('int', 'count'):
1945                 value = config.getint(pep8_section, opt)
1946             elif opt_type == 'string':
1947                 value = config.get(pep8_section, opt)
1948                 if normalized_opt == 'exclude':
1949                     value = normalize_paths(value, local_dir)
1950             else:
1951                 assert opt_type in ('store_true', 'store_false')
1952                 value = config.getboolean(pep8_section, opt)
1953             setattr(new_options, normalized_opt, value)
1954
1955         # Third, overwrite with the command-line options
1956         (options, __) = parser.parse_args(arglist, values=new_options)
1957     options.doctest = options.testsuite = False
1958     return options
1959
1960
1961 def process_options(arglist=None, parse_argv=False, config_file=None,
1962                     parser=None):
1963     """Process options passed either via arglist or via command line args."""
1964     if not parser:
1965         parser = get_parser()
1966     if not parser.has_option('--config'):
1967         if config_file is True:
1968             config_file = DEFAULT_CONFIG
1969         group = parser.add_option_group("Configuration", description=(
1970             "The project options are read from the [%s] section of the "
1971             "tox.ini file or the setup.cfg file located in any parent folder "
1972             "of the path(s) being processed.  Allowed options are: %s." %
1973             (parser.prog, ', '.join(parser.config_options))))
1974         group.add_option('--config', metavar='path', default=config_file,
1975                          help="user config file location (default: %default)")
1976     # Don't read the command line if the module is used as a library.
1977     if not arglist and not parse_argv:
1978         arglist = []
1979     # If parse_argv is True and arglist is None, arguments are
1980     # parsed from the command line (sys.argv)
1981     (options, args) = parser.parse_args(arglist)
1982     options.reporter = None
1983
1984     if options.ensure_value('testsuite', False):
1985         args.append(options.testsuite)
1986     elif not options.ensure_value('doctest', False):
1987         if parse_argv and not args:
1988             if options.diff or any(os.path.exists(name)
1989                                    for name in PROJECT_CONFIG):
1990                 args = ['.']
1991             else:
1992                 parser.error('input not specified')
1993         options = read_config(options, args, arglist, parser)
1994         options.reporter = parse_argv and options.quiet == 1 and FileReport
1995
1996     options.filename = options.filename and options.filename.split(',')
1997     options.exclude = normalize_paths(options.exclude)
1998     options.select = options.select and options.select.split(',')
1999     options.ignore = options.ignore and options.ignore.split(',')
2000
2001     if options.diff:
2002         options.reporter = DiffReport
2003         stdin = stdin_get_value()
2004         options.selected_lines = parse_udiff(stdin, options.filename, args[0])
2005         args = sorted(options.selected_lines)
2006
2007     return options, args
2008
2009
2010 def _main():
2011     """Parse options and run checks on Python source."""
2012     import signal
2013
2014     # Handle "Broken pipe" gracefully
2015     try:
2016         signal.signal(signal.SIGPIPE, lambda signum, frame: sys.exit(1))
2017     except AttributeError:
2018         pass    # not supported on Windows
2019
2020     pep8style = StyleGuide(parse_argv=True, config_file=True)
2021     options = pep8style.options
2022     if options.doctest or options.testsuite:
2023         from testsuite.support import run_tests
2024         report = run_tests(pep8style)
2025     else:
2026         report = pep8style.check_files()
2027     if options.statistics:
2028         report.print_statistics()
2029     if options.benchmark:
2030         report.print_benchmark()
2031     if options.testsuite and not options.quiet:
2032         report.print_results()
2033     if report.total_errors:
2034         if options.count:
2035             sys.stderr.write(str(report.total_errors) + '\n')
2036         sys.exit(1)
2037
2038 if __name__ == '__main__':
2039     _main()