[Python-Dev] [Python-checkins] cpython: Python 8: no pep8, no chocolate! (original) (raw)

Brett Cannon brett at snarky.ca
Fri Apr 1 14:07:18 EDT 2016


Are you planning on removing this after today? My worry about leaving it in is if it's a modified copy that follows your Python 8 April Fools joke then it will quite possibly trip people up who try and run pep8 but don't have it installed, leading them to wonder why the heck their imports are now all flagged as broken.

On Thu, 31 Mar 2016 at 14:40 victor.stinner <python-checkins at python.org> wrote:

https://hg.python.org/cpython/rev/9aedec2dbc01 changeset: 100818:9aedec2dbc01 user: Victor Stinner <victor.stinner at gmail.com> date: Thu Mar 31 23:30:53 2016 +0200 summary: Python 8: no pep8, no chocolate!

files: Include/patchlevel.h | 6 +- Lib/pep8.py | 2151 ++++++++++++++++++++++++++++++ Lib/site.py | 56 + 3 files changed, 2210 insertions(+), 3 deletions(-)

diff --git a/Include/patchlevel.h b/Include/patchlevel.h --- a/Include/patchlevel.h +++ b/Include/patchlevel.h @@ -16,14 +16,14 @@ /* Version parsed out into numeric values */ /--start constants--/ -#define PYMAJORVERSION 3 -#define PYMINORVERSION 6 +#define PYMAJORVERSION 8 +#define PYMINORVERSION 0 #define PYMICROVERSION 0 #define PYRELEASELEVEL PYRELEASELEVELALPHA #define PYRELEASESERIAL 0 /* Version as a string */ -#define PYVERSION "3.6.0a0" +#define PYVERSION "8.0.0a0" /--end constants--/ /* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2. diff --git a/Lib/pep8.py b/Lib/pep8.py new file mode 100644 --- /dev/null +++ b/Lib/pep8.py @@ -0,0 +1,2151 @@ +#!/usr/bin/env python +# pep8.py - Check Python source code formatting, according to PEP 8 +# Copyright (C) 2006-2009 Johann C. Rocholl <johann at rocholl.net> +# Copyright (C) 2009-2014 Florent Xicluna <florent.xicluna at gmail.com> +# Copyright (C) 2014-2016 Ian Lee <ianlee1521 at gmail.com> +# +# Permission is hereby granted, free of charge, to any person +# obtaining a copy of this software and associated documentation files +# (the "Software"), to deal in the Software without restriction, +# including without limitation the rights to use, copy, modify, merge, +# publish, distribute, sublicense, and/or sell copies of the Software, +# and to permit persons to whom the Software is furnished to do so, +# subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +r""" +Check Python source code formatting, according to PEP 8. + +For usage and a list of options, try this: +$ python pep8.py -h + +This program and its regression test suite live here: +https://github.com/pycqa/pep8 + +Groups of errors and warnings: +E errors +W warnings +100 indentation +200 whitespace +300 blank lines +400 imports +500 line length +600 deprecation +700 statements +900 syntax error +""" +from future import withstatement + +import os +import sys +import re +import time +import inspect +import keyword +import tokenize +from optparse import OptionParser +from fnmatch import fnmatch +try: + from configparser import RawConfigParser + from io import TextIOWrapper +except ImportError: + from ConfigParser import RawConfigParser + +version = '1.7.0' + +DEFAULTEXCLUDE = '.svn,CVS,.bzr,.hg,.git,pycache,.tox' +DEFAULTIGNORE = 'E121,E123,E126,E226,E24,E704' +try: + if sys.platform == 'win32': + USERCONFIG = os.path.expanduser(r'~.pep8') + else: + USERCONFIG = os.path.join( + os.getenv('XDGCONFIGHOME') or os.path.expanduser('~/.config'), + 'pep8' + ) +except ImportError: + USERCONFIG = None + +PROJECTCONFIG = ('setup.cfg', 'tox.ini', '.pep8') +TESTSUITEPATH = os.path.join(os.path.dirname(file), 'testsuite') +MAXLINELENGTH = 79 +REPORTFORMAT = { + 'default': '%(path)s:%(row)d:%(col)d: %(code)s %(text)s', + 'pylint': '%(path)s:%(row)d: [%(code)s] %(text)s', +} + +PyCFONLYAST = 1024 +SINGLETONS = frozenset(['False', 'None', 'True']) +KEYWORDS = frozenset(keyword.kwlist + ['print']) - SINGLETONS +UNARYOPERATORS = frozenset(['>>', '**', '*', '+', '-']) +ARITHMETICOP = frozenset(['**', '*', '/', '//', '+', '-']) +WSOPTIONALOPERATORS = ARITHMETICOP.union(['^', '&', '|', '<<', '>>', '%']) +WSNEEDEDOPERATORS = frozenset([ + '**=', '*=', '/=', '//=', '+=', '-=', '!=', '<>', '<', '>', + '%=', '^=', '&=', '|=', '==', '<=', '>=', '<<=', '>>=', '=']) +WHITESPACE = frozenset(' \t') +NEWLINE = frozenset([tokenize.NL, tokenize.NEWLINE]) +SKIPTOKENS = NEWLINE.union([tokenize.INDENT, tokenize.DEDENT]) +# ERRORTOKEN is triggered by backticks in Python 3 +SKIPCOMMENTS = SKIPTOKENS.union([tokenize.COMMENT, tokenize.ERRORTOKEN]) +BENCHMARKKEYS = ['directories', 'files', 'logical lines', 'physical lines'] + +INDENTREGEX = re.compile(r'([ \t]*)') +RAISECOMMAREGEX = re.compile(r'raise\s+\w+\s*,') +RERAISECOMMAREGEX = re.compile(r'raise\s+\w+\s*,.,\s\w+\s*$') +ERRORCODEREGEX = re.compile(r'\b[A-Z]\d{3}\b') +DOCSTRINGREGEX = re.compile(r'u?r?["']') +EXTRANEOUSWHITESPACEREGEX = re.compile(r'[[({] | []}),;:]') +WHITESPACEAFTERCOMMAREGEX = re.compile(r'[,;:]\s*(?: |\t)') +COMPARESINGLETONREGEX = re.compile(r'(\bNone|\bFalse|\bTrue)?\s*([=!]=)' + r'\s*(?(1)|(None|False|True))\b') +COMPARENEGATIVEREGEX = re.compile(r'\b(not)\s+[^][)(}{ ]+\s+(in|is)\s') +COMPARETYPEREGEX = re.compile(r'(?:[=!]=|is(?:\s+not)?)\s*type(?:s.\w+Type' + r'|\s(\s([^)][^ )])\s))') +KEYWORDREGEX = re.compile(r'(\s*)\b(?:%s)\b(\s*)' % r'|'.join(KEYWORDS)) +OPERATORREGEX = re.compile(r'(?:[^,\s])(\s*)(?:[-+/|!<=>%&^]+)(\s)') +LAMBDAREGEX = re.compile(r'\blambda\b') +HUNKREGEX = re.compile(r'^@@ -\d+(?:,\d+)? +(\d+)(?:,(\d+))? @@.*$') + +# Work around Python < 2.6 behaviour, which does not generate NL after_ _+# a comment which is on a line by itself._ _+COMMENTWITHNL = tokenize.generatetokens(['#\n'].pop).send(None)[1] ==_ _'#\n'_ _+_ _+_ _+##############################################################################_ _+# Plugins (check functions) for physical lines_ _+##############################################################################_ _+_ _+_ _+def tabsorspaces(physicalline, indentchar):_ _+ r"""Never mix tabs and spaces._ _+_ _+ The most popular way of indenting Python is with spaces only. The_ _+ second-most popular way is with tabs only. Code indented with a_ _mixture_ _+ of tabs and spaces should be converted to using spaces exclusively._ _When_ _+ invoking the Python command line interpreter with the -t option, it_ _issues_ _+ warnings about code that illegally mixes tabs and spaces. When using_ _-tt_ _+ these warnings become errors. These options are highly recommended!_ _+_ _+ Okay: if a == 0:\n a = 1\n b = 1_ _+ E101: if a == 0:\n a = 1\n\tb = 1_ _+ """_ _+ indent = INDENTREGEX.match(physicalline).group(1)_ _+ for offset, char in enumerate(indent):_ _+ if char != indentchar:_ _+ return offset, "E101 indentation contains mixed spaces and_ _tabs"_ _+_ _+_ _+def tabsobsolete(physicalline):_ _+ r"""For new projects, spaces-only are strongly recommended over tabs._ _+_ _+ Okay: if True:\n return_ _+ W191: if True:\n\treturn_ _+ """_ _+ indent = INDENTREGEX.match(physicalline).group(1)_ _+ if '\t' in indent:_ _+ return indent.index('\t'), "W191 indentation contains tabs"_ _+_ _+_ _+def trailingwhitespace(physicalline):_ _+ r"""Trailing whitespace is superfluous._ _+_ _+ The warning returned varies on whether the line itself is blank, for_ _easier_ _+ filtering for those who want to indent their blank lines._ _+_ _+ Okay: spam(1)\n#_ _+ W291: spam(1) \n#_ _+ W293: class Foo(object):\n \n bang = 12_ _+ """_ _+ physicalline = physicalline.rstrip('\n') # chr(10), newline_ _+ physicalline = physicalline.rstrip('\r') # chr(13), carriage_ _return_ _+ physicalline = physicalline.rstrip('\x0c') # chr(12), form feed, ^L_ _+ stripped = physicalline.rstrip(' \t\v')_ _+ if physicalline != stripped:_ _+ if stripped:_ _+ return len(stripped), "W291 trailing whitespace"_ _+ else:_ _+ return 0, "W293 blank line contains whitespace"_ _+_ _+_ _+def trailingblanklines(physicalline, lines, linenumber, totallines):_ _+ r"""Trailing blank lines are superfluous._ _+_ _+ Okay: spam(1)_ _+ W391: spam(1)\n_ _+_ _+ However the last line should end with a new line (warning W292)._ _+ """_ _+ if linenumber == totallines:_ _+ strippedlastline = physicalline.rstrip()_ _+ if not strippedlastline:_ _+ return 0, "W391 blank line at end of file"_ _+ if strippedlastline == physicalline:_ _+ return len(physicalline), "W292 no newline at end of file"_ _+_ _+_ _+def maximumlinelength(physicalline, maxlinelength, multiline):_ _+ r"""Limit all lines to a maximum of 79 characters._ _+_ _+ There are still many devices around that are limited to 80 character_ _+ lines; plus, limiting windows to 80 characters makes it possible to_ _have_ _+ several windows side-by-side. The default wrapping on such devices_ _looks_ _+ ugly. Therefore, please limit all lines to a maximum of 79_ _characters._ _+ For flowing long blocks of text (docstrings or comments), limiting the_ _+ length to 72 characters is recommended._ _+_ _+ Reports error E501._ _+ """_ _+ line = physicalline.rstrip()_ _+ length = len(line)_ _+ if length > maxlinelength and not noqa(line): + # Special case for long URLs in multi-line docstrings or comments, + # but still report the error when the 72 first chars are whitespaces. + chunks = line.split() + if ((len(chunks) == 1 and multiline) or _+ (len(chunks) == 2 and chunks[0] == '#')) and _ + len(line) - len(chunks[-1]) < maxlinelength - 7:_ _+ return_ _+ if hasattr(line, 'decode'): # Python 2_ _+ # The line could contain multi-byte characters_ _+ try:_ _+ length = len(line.decode('utf-8'))_ _+ except UnicodeError:_ _+ pass_ _+ if length > maxlinelength: + return (maxlinelength, "E501 line too long " + "(%d > %d characters)" % (length, maxlinelength)) + + +############################################################################## +# Plugins (check functions) for logical lines +############################################################################## + + +def blanklines(logicalline, blanklines, indentlevel, linenumber, + blankbefore, previouslogical, previousindentlevel): + r"""Separate top-level function and class definitions with two blank lines. + + Method definitions inside a class are separated by a single blank line. + + Extra blank lines may be used (sparingly) to separate groups of related + functions. Blank lines may be omitted between a bunch of related + one-liners (e.g. a set of dummy implementations). + + Use blank lines in functions, sparingly, to indicate logical sections. + + Okay: def a():\n pass\n\n\ndef b():\n pass + Okay: def a():\n pass\n\n\n# Foo\n# Bar\n\ndef b():\n pass + + E301: class Foo:\n b = 0\n def bar():\n pass + E302: def a():\n pass\n\ndef b(n):\n pass + E303: def a():\n pass\n\n\n\ndef b(n):\n pass + E303: def a():\n\n\n\n pass + E304: @decorator\n\ndef a():\n pass + """ + if linenumber < 3 and not previouslogical:_ _+ return # Don't expect blank lines before the first line_ _+ if previouslogical.startswith('@'):_ _+ if blanklines:_ _+ yield 0, "E304 blank lines found after function decorator"_ _+ elif blanklines > 2 or (indentlevel and blanklines == 2): + yield 0, "E303 too many blank lines (%d)" % blanklines + elif logicalline.startswith(('def ', 'class ', '@')): + if indentlevel: + if not (blankbefore or previousindentlevel < indentlevel_ _or_ _+ DOCSTRINGREGEX.match(previouslogical)):_ _+ yield 0, "E301 expected 1 blank line, found 0"_ _+ elif blankbefore != 2:_ _+ yield 0, "E302 expected 2 blank lines, found %d" %_ _blankbefore_ _+_ _+_ _+def extraneouswhitespace(logicalline):_ _+ r"""Avoid extraneous whitespace._ _+_ _+ Avoid extraneous whitespace in these situations:_ _+ - Immediately inside parentheses, brackets or braces._ _+ - Immediately before a comma, semicolon, or colon._ _+_ _+ Okay: spam(ham[1], {eggs: 2})_ _+ E201: spam( ham[1], {eggs: 2})_ _+ E201: spam(ham[ 1], {eggs: 2})_ _+ E201: spam(ham[1], { eggs: 2})_ _+ E202: spam(ham[1], {eggs: 2} )_ _+ E202: spam(ham[1 ], {eggs: 2})_ _+ E202: spam(ham[1], {eggs: 2 })_ _+_ _+ E203: if x == 4: print x, y; x, y = y , x_ _+ E203: if x == 4: print x, y ; x, y = y, x_ _+ E203: if x == 4 : print x, y; x, y = y, x_ _+ """_ _+ line = logicalline_ _+ for match in EXTRANEOUSWHITESPACEREGEX.finditer(line):_ _+ text = match.group()_ _+ char = text.strip()_ _+ found = match.start()_ _+ if text == char + ' ':_ _+ # assert char in '([{'_ _+ yield found + 1, "E201 whitespace after '%s'" % char_ _+ elif line[found - 1] != ',':_ _+ code = ('E202' if char in '}])' else 'E203') # if char in_ _',;:'_ _+ yield found, "%s whitespace before '%s'" % (code, char)_ _+_ _+_ _+def whitespacearoundkeywords(logicalline):_ _+ r"""Avoid extraneous whitespace around keywords._ _+_ _+ Okay: True and False_ _+ E271: True and False_ _+ E272: True and False_ _+ E273: True and\tFalse_ _+ E274: True\tand False_ _+ """_ _+ for match in KEYWORDREGEX.finditer(logicalline):_ _+ before, after = match.groups()_ _+_ _+ if '\t' in before:_ _+ yield match.start(1), "E274 tab before keyword"_ _+ elif len(before) > 1: + yield match.start(1), "E272 multiple spaces before keyword" + + if '\t' in after: + yield match.start(2), "E273 tab after keyword" + elif len(after) > 1: + yield match.start(2), "E271 multiple spaces after keyword" + + +def missingwhitespace(logicalline): + r"""Each comma, semicolon or colon should be followed by whitespace. + + Okay: [a, b] + Okay: (3,) + Okay: a[1:4] + Okay: a[:4] + Okay: a[1:] + Okay: a[1:4:2] + E231: ['a','b'] + E231: foo(bar,baz) + E231: [{'a':'b'}] + """ + line = logicalline + for index in range(len(line) - 1): + char = line[index] + if char in ',;:' and line[index + 1] not in WHITESPACE: + before = line[:index] _+ if char == ':' and before.count('[') > before.count(']') and _ + before.rfind('{') < before.rfind('['):_ _+ continue # Slice syntax, no space required_ _+ if char == ',' and line[index + 1] == ')':_ _+ continue # Allow tuple with only one element: (3,)_ _+ yield index, "E231 missing whitespace after '%s'" % char_ _+_ _+_ _+def indentation(logicalline, previouslogical, indentchar,_ _+ indentlevel, previousindentlevel):_ _+ r"""Use 4 spaces per indentation level._ _+_ _+ For really old code that you don't want to mess up, you can continue_ _to_ _+ use 8-space tabs._ _+_ _+ Okay: a = 1_ _+ Okay: if a == 0:\n a = 1_ _+ E111: a = 1_ _+ E114: # a = 1_ _+_ _+ Okay: for item in items:\n pass_ _+ E112: for item in items:\npass_ _+ E115: for item in items:\n# Hi\n pass_ _+_ _+ Okay: a = 1\nb = 2_ _+ E113: a = 1\n b = 2_ _+ E116: a = 1\n # b = 2_ _+ """_ _+ c = 0 if logicalline else 3_ _+ tmpl = "E11%d %s" if logicalline else "E11%d %s (comment)"_ _+ if indentlevel % 4:_ _+ yield 0, tmpl % (1 + c, "indentation is not a multiple of four")_ _+ indentexpect = previouslogical.endswith(':')_ _+ if indentexpect and indentlevel <= previousindentlevel:_ _+ yield 0, tmpl % (2 + c, "expected an indented block")_ _+ elif not indentexpect and indentlevel > previousindentlevel: + yield 0, tmpl % (3 + c, "unexpected indentation") + + +def continuedindentation(logicalline, tokens, indentlevel, hangclosing, + indentchar, noqa, verbose): + r"""Continuation lines indentation. + + Continuation lines should align wrapped elements either vertically + using Python's implicit line joining inside parentheses, brackets + and braces, or using a hanging indent. + + When using a hanging indent these considerations should be applied: + - there should be no arguments on the first line, and + - further indentation should be used to clearly distinguish itself as a + continuation line. + + Okay: a = (\n) + E123: a = (\n ) + + Okay: a = (\n 42) + E121: a = (\n 42) + E122: a = (\n42) + E123: a = (\n 42\n ) + E124: a = (24,\n 42\n) + E125: if (\n b):\n pass + E126: a = (\n 42) + E127: a = (24,\n 42) + E128: a = (24,\n 42) + E129: if (a or\n b):\n pass + E131: a = (\n 42\n 24) + """ + firstrow = tokens[0][2][0] + nrows = 1 + tokens[-1][2][0] - firstrow + if noqa or nrows == 1: + return + + # indentnext tells us whether the next block is indented; assuming + # that it is indented by 4 spaces, then we should not allow 4-space + # indents on the final continuation line; in turn, some other + # indents are allowed to have an extra 4 spaces. + indentnext = logicalline.endswith(':') + + row = depth = 0 + validhangs = (4,) if indentchar != '\t' else (4, 8) + # remember how many brackets were opened on each line + parens = [0] * nrows + # relative indents of physical lines + relindent = [0] * nrows + # for each depth, collect a list of opening rows + openrows = [[0]] + # for each depth, memorize the hanging indentation + hangs = [None] + # visual indents + indentchances = {} + lastindent = tokens[0][2] + visualindent = None + lasttokenmultiline = False + # for each depth, memorize the visual indent column + indent = [lastindent[1]] + if verbose >= 3: + print(">>> " + tokens[0][4].rstrip()) + + for tokentype, text, start, end, line in tokens: + + newline = row < start[0] - firstrow_ _+ if newline:_ _+ row = start[0] - firstrow_ _+ newline = not lasttokenmultiline and tokentype not in_ _NEWLINE_ _+_ _+ if newline:_ _+ # this is the beginning of a continuation line._ _+ lastindent = start_ _+ if verbose >= 3: + print("... " + line.rstrip()) + + # record the initial indent. + relindent[row] = expandindent(line) - indentlevel + + # identify closing bracket + closebracket = (tokentype == tokenize.OP and text in ']})') + + # is the indent relative to an opening bracket line? + for openrow in reversed(openrows[depth]): + hang = relindent[row] - relindent[openrow] + hangingindent = hang in validhangs + if hangingindent: + break + if hangs[depth]: + hangingindent = (hang == hangs[depth]) + # is there any chance of visual indent? + visualindent = (not closebracket and hang > 0 and + indentchances.get(start[1])) + + if closebracket and indent[depth]: + # closing bracket for visual indent + if start[1] != indent[depth]: + yield (start, "E124 closing bracket does not match " + "visual indentation") + elif closebracket and not hang: + # closing bracket matches indentation of opening bracket's line + if hangclosing: + yield start, "E133 closing bracket is missing indentation" + elif indent[depth] and start[1] < indent[depth]:_ _+ if visualindent is not True:_ _+ # visual indent is broken_ _+ yield (start, "E128 continuation line "_ _+ "under-indented for visual indent")_ _+ elif hangingindent or (indentnext and relindent[row] == 8):_ _+ # hanging indent is verified_ _+ if closebracket and not hangclosing:_ _+ yield (start, "E123 closing bracket does not match "_ _+ "indentation of opening bracket's line")_ _+ hangs[depth] = hang_ _+ elif visualindent is True:_ _+ # visual indent is verified_ _+ indent[depth] = start[1]_ _+ elif visualindent in (text, str):_ _+ # ignore token lined up with matching one from a previous_ _line_ _+ pass_ _+ else:_ _+ # indent is broken_ _+ if hang <= 0:_ _+ error = "E122", "missing indentation or outdented"_ _+ elif indent[depth]:_ _+ error = "E127", "over-indented for visual indent"_ _+ elif not closebracket and hangs[depth]:_ _+ error = "E131", "unaligned for hanging indent"_ _+ else:_ _+ hangs[depth] = hang_ _+ if hang > 4: + error = "E126", "over-indented for hanging indent" + else: + error = "E121", "under-indented for hanging indent" + yield start, "%s continuation line %s" % error + + # look for visual indenting + if (parens[row] and + tokentype not in (tokenize.NL, tokenize.COMMENT) and + not indent[depth]): + indent[depth] = start[1] + indentchances[start[1]] = True + if verbose >= 4: + print("bracket depth %s indent to %s" % (depth, start[1])) + # deal with implicit string concatenation + elif (tokentype in (tokenize.STRING, tokenize.COMMENT) or + text in ('u', 'ur', 'b', 'br')): + indentchances[start[1]] = str + # special case for the "if" statement because len("if (") == 4 + elif not indentchances and not row and not depth and text == 'if': + indentchances[end[1] + 1] = True + elif text == ':' and line[end[1]:].isspace(): + openrows[depth].append(row) + + # keep track of bracket depth + if tokentype == tokenize.OP: + if text in '([{': + depth += 1 + indent.append(0) + hangs.append(None) + if len(openrows) == depth: + openrows.append([]) + openrows[depth].append(row) + parens[row] += 1 + if verbose >= 4: + print("bracket depth %s seen, col %s, visual min = %s" % + (depth, start[1], indent[depth])) + elif text in ')]}' and depth > 0: + # parent indents should not be more than this one + previndent = indent.pop() or lastindent[1] + hangs.pop() + for d in range(depth): + if indent[d] > previndent: + indent[d] = 0 + for ind in list(indentchances): + if ind >= previndent: + del indentchances[ind] + del openrows[depth + 1:] + depth -= 1 + if depth: + indentchances[indent[depth]] = True + for idx in range(row, -1, -1): + if parens[idx]: + parens[idx] -= 1 + break + assert len(indent) == depth + 1 + if start[1] not in indentchances: + # allow to line up tokens + indentchances[start[1]] = text + + lasttokenmultiline = (start[0] != end[0]) + if lasttokenmultiline: + relindent[end[0] - firstrow] = relindent[row] + + if indentnext and expandindent(line) == indentlevel + 4: + pos = (start[0], indent[0] + 4) + if visualindent: + code = "E129 visually indented line" + else: + code = "E125 continuation line" + yield pos, "%s with same indent as next logical line" % code + + +def whitespacebeforeparameters(logicalline, tokens): + r"""Avoid extraneous whitespace. + + Avoid extraneous whitespace in the following situations: + - before the open parenthesis that starts the argument list of a + function call. + - before the open parenthesis that starts an indexing or slicing. + + Okay: spam(1) + E211: spam (1) + + Okay: dict['key'] = list[index] + E211: dict ['key'] = list[index] + E211: dict['key'] = list [index] + """ _+ prevtype, prevtext, , prevend, _ = tokens[0] + for index in range(1, len(tokens)): + tokentype, text, start, end, _ = tokens[index] + if (tokentype == tokenize.OP and + text in '([' and + start != prevend and + (prevtype == tokenize.NAME or prevtext in '}])') and + # Syntax "class A (B):" is allowed, but avoid it + (index < 2 or tokens[index - 2][1] != 'class') and_ _+ # Allow "return (a.foo for a in range(5))"_ _+ not keyword.iskeyword(prevtext)):_ _+ yield prevend, "E211 whitespace before '%s'" % text_ _+ prevtype = tokentype_ _+ prevtext = text_ _+ prevend = end_ _+_ _+_ _+def whitespacearoundoperator(logicalline):_ _+ r"""Avoid extraneous whitespace around an operator._ _+_ _+ Okay: a = 12 + 3_ _+ E221: a = 4 + 5_ _+ E222: a = 4 + 5_ _+ E223: a = 4\t+ 5_ _+ E224: a = 4 +\t5_ _+ """_ _+ for match in OPERATORREGEX.finditer(logicalline):_ _+ before, after = match.groups()_ _+_ _+ if '\t' in before:_ _+ yield match.start(1), "E223 tab before operator"_ _+ elif len(before) > 1: + yield match.start(1), "E221 multiple spaces before operator" + + if '\t' in after: + yield match.start(2), "E224 tab after operator" + elif len(after) > 1: + yield match.start(2), "E222 multiple spaces after operator" + + +def missingwhitespacearoundoperator(logicalline, tokens): + r"""Surround operators with a single space on either side. + + - Always surround these binary operators with a single space on + either side: assignment (=), augmented assignment (+=, -= etc.), + comparisons (==, <, >, !=, <=, >=, in, not in, is, is not), + Booleans (and, or, not). + + - If operators with different priorities are used, consider adding + whitespace around the operators with the lowest priorities. + + Okay: i = i + 1 + Okay: submitted += 1 + Okay: x = x * 2 - 1 + Okay: hypot2 = x * x + y * y + Okay: c = (a + b) * (a - b) + Okay: foo(bar, key='word', *args, **kwargs) + Okay: alpha[:-i] + + E225: i=i+1 + E225: submitted +=1 + E225: x = x /2 - 1 + E225: z = x **y + E226: c = (a+b) * (a-b) + E226: hypot2 = xx + yy + E227: c = a|b + E228: msg = fmt%(errno, errmsg) + """ + parens = 0 + needspace = False + prevtype = tokenize.OP + prevtext = prevend = None + for tokentype, text, start, end, line in tokens: + if tokentype in SKIPCOMMENTS: + continue + if text in ('(', 'lambda'): + parens += 1 + elif text == ')': + parens -= 1 + if needspace: + if start != prevend: + # Found a (probably) needed space + if needspace is not True and not needspace[1]: + yield (needspace[0], + "E225 missing whitespace around operator") + needspace = False + elif text == '>' and prevtext in ('<', '-'):_ _+ # Tolerate the "<>" operator, even if running Python 3 + # Deal with Python 3's annotated return value "->" + pass + else: + if needspace is True or needspace[1]: + # A needed trailing space was not found + yield prevend, "E225 missing whitespace around operator" + elif prevtext != '**': + code, optype = 'E226', 'arithmetic' + if prevtext == '%': + code, optype = 'E228', 'modulo' + elif prevtext not in ARITHMETICOP: + code, optype = 'E227', 'bitwise or shift' + yield (needspace[0], "%s missing whitespace " + "around %s operator" % (code, optype)) + needspace = False + elif tokentype == tokenize.OP and prevend is not None: + if text == '=' and parens: + # Allow keyword args or defaults: foo(bar=None). + pass + elif text in WSNEEDEDOPERATORS: + needspace = True + elif text in UNARYOPERATORS: + # Check if the operator is being used as a binary operator + # Allow unary operators: -123, -x, +1. + # Allow argument unpacking: foo(*args, **kwargs). + if (prevtext in '}])' if prevtype == tokenize.OP + else prevtext not in KEYWORDS): + needspace = None + elif text in WSOPTIONALOPERATORS: + needspace = None + + if needspace is None: + # Surrounding space is optional, but ensure that + # trailing space matches opening space + needspace = (prevend, start != prevend) + elif needspace and start == prevend: + # A needed opening space was not found + yield prevend, "E225 missing whitespace around operator" + needspace = False + prevtype = tokentype + prevtext = text + prevend = end + + +def whitespacearoundcomma(logicalline): + r"""Avoid extraneous whitespace after a comma or a colon. + + Note: these checks are disabled by default + + Okay: a = (1, 2) + E241: a = (1, 2) + E242: a = (1,\t2) + """ + line = logicalline + for m in WHITESPACEAFTERCOMMAREGEX.finditer(line): + found = m.start() + 1 + if '\t' in m.group(): + yield found, "E242 tab after '%s'" % m.group()[0] + else: + yield found, "E241 multiple spaces after '%s'" % m.group()[0] + + +def whitespacearoundnamedparameterequals(logicalline, tokens): + r"""Don't use spaces around the '=' sign in function arguments. + + Don't use spaces around the '=' sign when used to indicate a + keyword argument or a default parameter value. + + Okay: def complex(real, imag=0.0): + Okay: return magic(r=real, i=imag) + Okay: boolean(a == b) + Okay: boolean(a != b) + Okay: boolean(a <= b)_ _+ Okay: boolean(a >= b) + Okay: def foo(arg: int = 42): + + E251: def complex(real, imag = 0.0): + E251: return magic(r = real, i = imag) + """ + parens = 0 + nospace = False + prevend = None + annotatedfuncarg = False + indef = logicalline.startswith('def') + message = "E251 unexpected spaces around keyword / parameter equals" + for tokentype, text, start, end, line in tokens: + if tokentype == tokenize.NL: + continue + if nospace: + nospace = False + if start != prevend: + yield (prevend, message) + if tokentype == tokenize.OP: + if text == '(': + parens += 1 + elif text == ')': + parens -= 1 + elif indef and text == ':' and parens == 1: + annotatedfuncarg = True + elif parens and text == ',' and parens == 1: + annotatedfuncarg = False + elif parens and text == '=' and not annotatedfuncarg: + nospace = True + if start != prevend: + yield (prevend, message) + if not parens: + annotatedfuncarg = False + + prevend = end + + +def whitespacebeforecomment(logicalline, tokens): + r"""Separate inline comments by at least two spaces. + + An inline comment is a comment on the same line as a statement. Inline + comments should be separated by at least two spaces from the statement. + They should start with a # and a single space. + + Each line of a block comment starts with a # and a single space + (unless it is indented text inside the comment). + + Okay: x = x + 1 # Increment x + Okay: x = x + 1 # Increment x + Okay: # Block comment + E261: x = x + 1 # Increment x + E262: x = x + 1 #Increment x + E262: x = x + 1 # Increment x + E265: #Block comment + E266: ### Block comment + """ + prevend = (0, 0) + for tokentype, text, start, end, line in tokens: + if tokentype == tokenize.COMMENT: + inlinecomment = line[:start[1]].strip() + if inlinecomment: + if prevend[0] == start[0] and start[1] < prevend[1] + 2:_ _+ yield (prevend,_ _+ "E261 at least two spaces before inline_ _comment")_ _+ symbol, sp, comment = text.partition(' ')_ _+ badprefix = symbol not in '#:' and (symbol.lstrip('#')[:1]_ _or '#')_ _+ if inlinecomment:_ _+ if badprefix or comment[:1] in WHITESPACE:_ _+ yield start, "E262 inline comment should start with_ _'# '"_ _+ elif badprefix and (badprefix != '!' or start[0] > 1): + if badprefix != '#': + yield start, "E265 block comment should start with '# '" + elif comment: + yield start, "E266 too many leading '#' for block comment" + elif tokentype != tokenize.NL: + prevend = end + + +def importsonseparatelines(logicalline): + r"""Imports should usually be on separate lines. + + Okay: import os\nimport sys + E401: import sys, os + + Okay: from subprocess import Popen, PIPE + Okay: from myclas import MyClass + Okay: from foo.bar.yourclass import YourClass + Okay: import myclass + Okay: import foo.bar.yourclass + """ + line = logicalline + if line.startswith('import '): + found = line.find(',') + if -1 < found and ';' not in line[:found]:_ _+ yield found, "E401 multiple imports on one line"_ _+_ _+_ _+def moduleimportsontopoffile(_ _+ logicalline, indentlevel, checkerstate, noqa):_ _+ r"""Imports are always put at the top of the file, just after any_ _module_ _+ comments and docstrings, and before module globals and constants._ _+_ _+ Okay: import os_ _+ Okay: # this is a comment\nimport os_ _+ Okay: '''this is a module docstring'''\nimport os_ _+ Okay: r'''this is a module docstring'''\nimport os_ _+ Okay: try:\n import x\nexcept:\n pass\nelse:\n pass\nimport y_ _+ Okay: try:\n import x\nexcept:\n pass\nfinally:\n_ _pass\nimport y_ _+ E402: a=1\nimport os_ _+ E402: 'One string'\n"Two string"\nimport os_ _+ E402: a=1\nfrom sys import x_ _+_ _+ Okay: if x:\n import os_ _+ """_ _+ def isstringliteral(line):_ _+ if line[0] in 'uUbB':_ _+ line = line[1:]_ _+ if line and line[0] in 'rR':_ _+ line = line[1:]_ _+ return line and (line[0] == '"' or line[0] == "'")_ _+_ _+ allowedtrykeywords = ('try', 'except', 'else', 'finally')_ _+_ _+ if indentlevel: # Allow imports in conditional statements or_ _functions_ _+ return_ _+ if not logicalline: # Allow empty lines or comments_ _+ return_ _+ if noqa:_ _+ return_ _+ line = logicalline_ _+ if line.startswith('import ') or line.startswith('from '):_ _+ if checkerstate.get('seennonimports', False):_ _+ yield 0, "E402 module level import not at top of file"_ _+ elif any(line.startswith(kw) for kw in allowedtrykeywords):_ _+ # Allow try, except, else, finally keywords intermixed with_ _imports in_ _+ # order to support conditional importing_ _+ return_ _+ elif isstringliteral(line):_ _+ # The first literal is a docstring, allow it. Otherwise, report_ _error._ _+ if checkerstate.get('seendocstring', False):_ _+ checkerstate['seennonimports'] = True_ _+ else:_ _+ checkerstate['seendocstring'] = True_ _+ else:_ _+ checkerstate['seennonimports'] = True_ _+_ _+_ _+def compoundstatements(logicalline):_ _+ r"""Compound statements (on the same line) are generally discouraged._ _+_ _+ While sometimes it's okay to put an if/for/while with a small body_ _+ on the same line, never do this for multi-clause statements._ _+ Also avoid folding such long lines!_ _+_ _+ Always use a def statement instead of an assignment statement that_ _+ binds a lambda expression directly to a name._ _+_ _+ Okay: if foo == 'blah':\n doblahthing()_ _+ Okay: doone()_ _+ Okay: dotwo()_ _+ Okay: dothree()_ _+_ _+ E701: if foo == 'blah': doblahthing()_ _+ E701: for x in lst: total += x_ _+ E701: while t < 10: t = delay()_ _+ E701: if foo == 'blah': doblahthing()_ _+ E701: else: dononblahthing()_ _+ E701: try: something()_ _+ E701: finally: cleanup()_ _+ E701: if foo == 'blah': one(); two(); three()_ _+ E702: doone(); dotwo(); dothree()_ _+ E703: dofour(); # useless semicolon_ _+ E704: def f(x): return 2*x_ _+ E731: f = lambda x: 2*x_ _+ """_ _+ line = logicalline_ _+ lastchar = len(line) - 1_ _+ found = line.find(':')_ _+ while -1 < found < lastchar:_ _+ before = line[:found]_ _+ if ((before.count('{') <= before.count('}') and # {'a': 1}_ _(dict)_ _+ before.count('[') <= before.count(']') and # [1:2] (slice)_ _+ before.count('(') <= before.count(')'))): # (annotation)_ _+ lambdakw = LAMBDAREGEX.search(before)_ _+ if lambdakw:_ _+ before = line[:lambdakw.start()].rstrip()_ _+ if before[-1:] == '=' and_ _isidentifier(before[:-1].strip()):_ _+ yield 0, ("E731 do not assign a lambda expression,_ _use a "_ _+ "def")_ _+ break_ _+ if before.startswith('def '):_ _+ yield 0, "E704 multiple statements on one line (def)"_ _+ else:_ _+ yield found, "E701 multiple statements on one line_ _(colon)"_ _+ found = line.find(':', found + 1)_ _+ found = line.find(';')_ _+ while -1 < found:_ _+ if found < lastchar:_ _+ yield found, "E702 multiple statements on one line_ _(semicolon)"_ _+ else:_ _+ yield found, "E703 statement ends with a semicolon"_ _+ found = line.find(';', found + 1)_ _+_ _+_ _+def explicitlinejoin(logicalline, tokens):_ _+ r"""Avoid explicit line join between brackets._ _+_ _+ The preferred way of wrapping long lines is by using Python's implied_ _line_ _+ continuation inside parentheses, brackets and braces. Long lines can_ _be_ _+ broken over multiple lines by wrapping expressions in parentheses._ _These_ _+ should be used in preference to using a backslash for line_ _continuation._ _+_ _+ E502: aaa = [123, \n 123]_ _+ E502: aaa = ("bbb " \n "ccc")_ _+_ _+ Okay: aaa = [123,\n 123]_ _+ Okay: aaa = ("bbb "\n "ccc")_ _+ Okay: aaa = "bbb " \n "ccc"_ _+ Okay: aaa = 123 # \_ _+ """_ _+ prevstart = prevend = parens = 0_ _+ comment = False_ _+ backslash = None_ _+ for tokentype, text, start, end, line in tokens:_ _+ if tokentype == tokenize.COMMENT:_ _+ comment = True_ _+ if start[0] != prevstart and parens and backslash and not_ _comment:_ _+ yield backslash, "E502 the backslash is redundant between_ _brackets"_ _+ if end[0] != prevend:_ _+ if line.rstrip('\r\n').endswith('\'):_ _+ backslash = (end[0], len(line.splitlines()[-1]) - 1)_ _+ else:_ _+ backslash = None_ _+ prevstart = prevend = end[0]_ _+ else:_ _+ prevstart = start[0]_ _+ if tokentype == tokenize.OP:_ _+ if text in '([{':_ _+ parens += 1_ _+ elif text in ')]}':_ _+ parens -= 1_ _+_ _+_ _+def breakaroundbinaryoperator(logicalline, tokens):_ _+ r"""_ _+ Avoid breaks before binary operators._ _+_ _+ The preferred place to break around a binary operator is after the_ _+ operator, not before it._ _+_ _+ W503: (width == 0\n + height == 0)_ _+ W503: (width == 0\n and height == 0)_ _+_ _+ Okay: (width == 0 +\n height == 0)_ _+ Okay: foo(\n -x)_ _+ Okay: foo(x\n [])_ _+ Okay: x = '''\n''' + ''_ _+ Okay: foo(x,\n -y)_ _+ Okay: foo(x, # comment\n -y)_ _+ """_ _+ def isbinaryoperator(tokentype, text):_ _+ # The % character is strictly speaking a binary operator, but the_ _+ # common usage seems to be to put it next to the format_ _parameters,_ _+ # after a line break._ _+ return ((tokentype == tokenize.OP or text in ['and', 'or']) and_ _+ text not in "()[]{},:.;@=%")_ _+_ _+ linebreak = False_ _+ unarycontext = True_ _+ for tokentype, text, start, end, line in tokens:_ _+ if tokentype == tokenize.COMMENT:_ _+ continue_ _+ if ('\n' in text or '\r' in text) and tokentype !=_ _tokenize.STRING:_ _+ linebreak = True_ _+ else:_ _+ if (isbinaryoperator(tokentype, text) and linebreak and_ _+ not unarycontext):_ _+ yield start, "W503 line break before binary operator"_ _+ unarycontext = text in '([{,;'_ _+ linebreak = False_ _+_ _+_ _+def comparisontosingleton(logicalline, noqa):_ _+ r"""Comparison to singletons should use "is" or "is not"._ _+_ _+ Comparisons to singletons like None should always be done_ _+ with "is" or "is not", never the equality operators._ _+_ _+ Okay: if arg is not None:_ _+ E711: if arg != None:_ _+ E711: if None == arg:_ _+ E712: if arg == True:_ _+ E712: if False == arg:_ _+_ _+ Also, beware of writing if x when you really mean if x is not None --_ _+ e.g. when testing whether a variable or argument that defaults to_ _None was_ _+ set to some other value. The other value might have a type (such as a_ _+ container) that could be false in a boolean context!_ _+ """_ _+ match = not noqa and COMPARESINGLETONREGEX.search(logicalline)_ _+ if match:_ _+ singleton = match.group(1) or match.group(3)_ _+ same = (match.group(2) == '==')_ _+_ _+ msg = "'if cond is %s:'" % (('' if same else 'not ') + singleton)_ _+ if singleton in ('None',):_ _+ code = 'E711'_ _+ else:_ _+ code = 'E712'_ _+ nonzero = ((singleton == 'True' and same) or_ _+ (singleton == 'False' and not same))_ _+ msg += " or 'if %scond:'" % ('' if nonzero else 'not ')_ _+ yield match.start(2), ("%s comparison to %s should be %s" %_ _+ (code, singleton, msg))_ _+_ _+_ _+def comparisonnegative(logicalline):_ _+ r"""Negative comparison should be done using "not in" and "is not"._ _+_ _+ Okay: if x not in y:\n pass_ _+ Okay: assert (X in Y or X is Z)_ _+ Okay: if not (X in Y):\n pass_ _+ Okay: zz = x is not y_ _+ E713: Z = not X in Y_ _+ E713: if not X.B in Y:\n pass_ _+ E714: if not X is Y:\n pass_ _+ E714: Z = not X.B is Y_ _+ """_ _+ match = COMPARENEGATIVEREGEX.search(logicalline)_ _+ if match:_ _+ pos = match.start(1)_ _+ if match.group(2) == 'in':_ _+ yield pos, "E713 test for membership should be 'not in'"_ _+ else:_ _+ yield pos, "E714 test for object identity should be 'is not'"_ _+_ _+_ _+def comparisontype(logicalline, noqa):_ _+ r"""Object type comparisons should always use isinstance()._ _+_ _+ Do not compare types directly._ _+_ _+ Okay: if isinstance(obj, int):_ _+ E721: if type(obj) is type(1):_ _+_ _+ When checking if an object is a string, keep in mind that it might be_ _a_ _+ unicode string too! In Python 2.3, str and unicode have a common base_ _+ class, basestring, so you can do:_ _+_ _+ Okay: if isinstance(obj, basestring):_ _+ Okay: if type(a1) is type(b1):_ _+ """_ _+ match = COMPARETYPEREGEX.search(logicalline)_ _+ if match and not noqa:_ _+ inst = match.group(1)_ _+ if inst and isidentifier(inst) and inst not in SINGLETONS:_ _+ return # Allow comparison for types which are not obvious_ _+ yield match.start(), "E721 do not compare types, use_ _'isinstance()'"_ _+_ _+_ _+def python3000haskey(logicalline, noqa):_ _+ r"""The {}.haskey() method is removed in Python 3: use the 'in'_ _operator._ _+_ _+ Okay: if "alph" in d:\n print d["alph"]_ _+ W601: assert d.haskey('alph')_ _+ """_ _+ pos = logicalline.find('.haskey(')_ _+ if pos > -1 and not noqa: + yield pos, "W601 .haskey() is deprecated, use 'in'" + + +def python3000raisecomma(logicalline): + r"""When raising an exception, use "raise ValueError('message')". + + The older form is removed in Python 3. + + Okay: raise DummyError("Message") + W602: raise DummyError, "Message" + """ + match = RAISECOMMAREGEX.match(logicalline) + if match and not RERAISECOMMAREGEX.match(logicalline): + yield match.end() - 1, "W602 deprecated form of raising exception" + + +def python3000notequal(logicalline): + r"""New code should always use != instead of <>. + + The older syntax is removed in Python 3. + + Okay: if a != 'no': + W603: if a <> 'no': + """ + pos = logicalline.find('<>') + if pos > -1: + yield pos, "W603 '<>' is deprecated, use '!='" + + +def python3000backticks(logicalline): + r"""Backticks are removed in Python 3: use repr() instead. + + Okay: val = repr(1 + 2) + W604: val = 1 + 2 + """ + pos = logicalline.find('`') + if pos > -1: + yield pos, "W604 backticks are deprecated, use 'repr()'" + + +############################################################################## +# Helper functions +############################################################################## + + +if sys.versioninfo < (3,):_ _+ # Python 2: implicit encoding._ _+ def readlines(filename):_ _+ """Read the source code."""_ _+ with open(filename, 'rU') as f:_ _+ return f.readlines()_ _+ isidentifier = re.compile(r'[a-zA-Z]\w*$').match_ _+ stdingetvalue = sys.stdin.read_ _+else:_ _+ # Python 3_ _+ def readlines(filename):_ _+ """Read the source code."""_ _+ try:_ _+ with open(filename, 'rb') as f:_ _+ (coding, lines) = tokenize.detectencoding(f.readline)_ _+ f = TextIOWrapper(f, coding, linebuffering=True)_ _+ return [l.decode(coding) for l in lines] + f.readlines()_ _+ except (LookupError, SyntaxError, UnicodeError):_ _+ # Fall back if file encoding is improperly declared_ _+ with open(filename, encoding='latin-1') as f:_ _+ return f.readlines()_ _+ isidentifier = str.isidentifier_ _+_ _+ def stdingetvalue():_ _+ return TextIOWrapper(sys.stdin.buffer, errors='ignore').read()_ _+noqa = re.compile(r'# no(?:qa|pep8)\b', re.I).search_ _+_ _+_ _+def expandindent(line):_ _+ r"""Return the amount of indentation._ _+_ _+ Tabs are expanded to the next multiple of 8._ _+_ _+ >>> expandindent(' ') + 4 + >>> expandindent('\t') + 8 + >>> expandindent(' \t') + 8 + >>> expandindent(' \t') + 16 + """ + if '\t' not in line: + return len(line) - len(line.lstrip()) + result = 0 + for char in line: + if char == '\t': + result = result // 8 * 8 + 8 + elif char == ' ': + result += 1 + else: + break + return result + + +def mutestring(text): + """Replace contents with 'xxx' to prevent syntax matching. + + >>> mutestring('"abc"') + '"xxx"' + >>> mutestring("'''abc'''") + "'''xxx'''" + >>> mutestring("r'abc'") + "r'xxx'" + """ + # String modifiers (e.g. u or r) + start = text.index(text[-1]) + 1 + end = len(text) - 1 + # Triple quotes + if text[-3:] in ('"""', "'''"): + start += 2 + end -= 2 + return text[:start] + 'x' * (end - start) + text[end:] + + +def parseudiff(diff, patterns=None, parent='.'): + """Return a dictionary of matching lines.""" + # For each file of the diff, the entry key is the filename, + # and the value is a set of row numbers to consider. + rv = {} + path = nrows = None + for line in diff.splitlines(): + if nrows: + if line[:1] != '-': + nrows -= 1 + continue + if line[:3] == '@@ ': + hunkmatch = HUNKREGEX.match(line) + (row, nrows) = [int(g or '1') for g in hunkmatch.groups()] + rv[path].update(range(row, row + nrows)) + elif line[:3] == '+++': + path = line[4:].split('\t', 1)[0] + if path[:2] == 'b/': + path = path[2:] + rv[path] = set() + return dict([(os.path.join(parent, path), rows) + for (path, rows) in rv.items() + if rows and filenamematch(path, patterns)]) + + +def normalizepaths(value, parent=os.curdir): + """Parse a comma-separated list of paths. + + Return a list of absolute paths. + """ + if not value: + return [] + if isinstance(value, list): + return value + paths = [] + for path in value.split(','): + path = path.strip() + if '/' in path: + path = os.path.abspath(os.path.join(parent, path)) + paths.append(path.rstrip('/')) + return paths + + +def filenamematch(filename, patterns, default=True): + """Check if patterns contains a pattern that matches filename. + + If patterns is unspecified, this always returns True. + """ + if not patterns: + return default + return any(fnmatch(filename, pattern) for pattern in patterns) + + +def iseoltoken(token): + return token[0] in NEWLINE or token[4][token[3][1]:].lstrip() == '\\n' +if COMMENTWITHNL: + def iseoltoken(token, eoltoken=iseoltoken): + return eoltoken(token) or (token[0] == tokenize.COMMENT and + token[1] == token[4]) + +############################################################################## +# Framework to run all checks +############################################################################## + + +checks = {'physicalline': {}, 'logicalline': {}, 'tree': {}} + + +def getparameters(function): + if sys.versioninfo >= (3, 3): + return [parameter.name + for parameter + in inspect.signature(function).parameters.values() + if parameter.kind == parameter.POSITIONALORKEYWORD] + else: + return inspect.getargspec(function)[0] + + +def registercheck(check, codes=None): + """Register a new check object.""" + def addcheck(check, kind, codes, args): + if check in checks[kind]: + checks[kind][check][0].extend(codes or []) + else: + checks[kind][check] = (codes or [''], args) + if inspect.isfunction(check): + args = getparameters(check) + if args and args[0] in ('physicalline', 'logicalline'): + if codes is None: + codes = ERRORCODEREGEX.findall(check.doc or '') + addcheck(check, args[0], codes, args) + elif inspect.isclass(check): + if getparameters(check.init)[:2] == ['self', 'tree']: + addcheck(check, 'tree', codes, None) + + +def initchecksregistry(): + """Register all globally visible functions. + + The first argument name is either 'physicalline' or 'logicalline'. + """ + mod = inspect.getmodule(registercheck) + for (name, function) in inspect.getmembers(mod, inspect.isfunction): + registercheck(function) +initchecksregistry() + + +class Checker(object): + """Load a Python source file, tokenize it, check coding style.""" + + def init(self, filename=None, lines=None, + options=None, report=None, **kwargs): + if options is None: + options = StyleGuide(kwargs).options + else: + assert not kwargs + self.ioerror = None + self.physicalchecks = options.physicalchecks + self.logicalchecks = options.logicalchecks + self.astchecks = options.astchecks + self.maxlinelength = options.maxlinelength + self.multiline = False # in a multiline string? + self.hangclosing = options.hangclosing + self.verbose = options.verbose + self.filename = filename + # Dictionary where a checker can store its custom state. + self.checkerstates = {} + if filename is None: + self.filename = 'stdin' + self.lines = lines or [] + elif filename == '-': + self.filename = 'stdin' + self.lines = stdingetvalue().splitlines(True) + elif lines is None: + try: + self.lines = readlines(filename) + except IOError: + (exctype, exc) = sys.excinfo()[:2] + self.ioerror = '%s: %s' % (exctype.name, exc) + self.lines = [] + else: + self.lines = lines + if self.lines: + ord0 = ord(self.lines[0][0]) + if ord0 in (0xef, 0xfeff): # Strip the UTF-8 BOM + if ord0 == 0xfeff: + self.lines[0] = self.lines[0][1:] + elif self.lines[0][:3] == '\xef\xbb\xbf': + self.lines[0] = self.lines[0][3:] + self.report = report or options.report + self.reporterror = self.report.error + + def reportinvalidsyntax(self): + """Check if the syntax is valid.""" + (exctype, exc) = sys.excinfo()[:2] + if len(exc.args) > 1: + offset = exc.args[1] + if len(offset) > 2: + offset = offset[1:3] + else: + offset = (1, 0) + self.reporterror(offset[0], offset[1] or 0, + 'E901 %s: %s' % (exctype.name, exc.args[0]), + self.reportinvalidsyntax) + + def readline(self): + """Get the next line from the input buffer.""" + if self.linenumber >= self.totallines: + return '' + line = self.lines[self.linenumber] + self.linenumber += 1 + if self.indentchar is None and line[:1] in WHITESPACE: + self.indentchar = line[0] + return line + + def runcheck(self, check, argumentnames): + """Run a check plugin.""" + arguments = [] + for name in argumentnames: + arguments.append(getattr(self, name)) + return check(*arguments) + + def initcheckerstate(self, name, argumentnames): + """ Prepares a custom state for the specific checker plugin.""" + if 'checkerstate' in argumentnames: + self.checkerstate = self.checkerstates.setdefault(name, {}) + + def checkphysical(self, line): + """Run all physical checks on a raw input line.""" + self.physicalline = line + for name, check, argumentnames in self.physicalchecks: + self.initcheckerstate(name, argumentnames) + result = self.runcheck(check, argumentnames) + if result is not None: + (offset, text) = result + self.reporterror(self.linenumber, offset, text, check) + if text[:4] == 'E101': + self.indentchar = line[0] + + def buildtokensline(self): + """Build a logical line from tokens.""" + logical = [] + comments = [] + length = 0 + prevrow = prevcol = mapping = None + for tokentype, text, start, end, line in self.tokens: + if tokentype in SKIPTOKENS: + continue + if not mapping: + mapping = [(0, start)] + if tokentype == tokenize.COMMENT: + comments.append(text) + continue + if tokentype == tokenize.STRING: + text = mutestring(text) + if prevrow: + (startrow, startcol) = start + if prevrow != startrow: # different row + prevtext = self.lines[prevrow - 1][prevcol - 1] + if prevtext == ',' or (prevtext not in '{[(' and + text not in '}])'): + text = ' ' + text + elif prevcol != startcol: # different column + text = line[prevcol:startcol] + text + logical.append(text) + length += len(text) + mapping.append((length, end)) + (prevrow, prevcol) = end + self.logicalline = ''.join(logical) + self.noqa = comments and noqa(''.join(comments)) + return mapping + + def checklogical(self): + """Build a line from tokens and run all logical checks on it.""" + self.report.incrementlogicalline() + mapping = self.buildtokensline() + + if not mapping: + return + + (startrow, startcol) = mapping[0][1] + startline = self.lines[startrow - 1] + self.indentlevel = expandindent(startline[:startcol]) + if self.blankbefore < self.blanklines:_ _+ self.blankbefore = self.blanklines_ _+ if self.verbose >= 2: + print(self.logicalline[:80].rstrip()) + for name, check, argumentnames in self.logicalchecks: + if self.verbose >= 4: + print(' ' + name) + self.initcheckerstate(name, argumentnames) + for offset, text in self.runcheck(check, argumentnames) or (): + if not isinstance(offset, tuple): + for tokenoffset, pos in mapping: _+ if offset <= tokenoffset:_ _+ break_ _+ offset = (pos[0], pos[1] + offset - tokenoffset)_ _+ self.reporterror(offset[0], offset[1], text, check)_ _+ if self.logicalline:_ _+ self.previousindentlevel = self.indentlevel_ _+ self.previouslogical = self.logicalline_ _+ self.blanklines = 0_ _+ self.tokens = []_ _+_ _+ def checkast(self):_ _+ """Build the file's AST and run all AST checks."""_ _+ try:_ _+ tree = compile(''.join(self.lines), '', 'exec', PyCFONLYAST)_ _+ except (ValueError, SyntaxError, TypeError):_ _+ return self.reportinvalidsyntax()_ _+ for name, cls, _ in self.a_ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20160401/6d0aed6f/attachment-0001.html>



More information about the Python-Dev mailing list