pycodestyle-2.3.1.py 87 KB

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