Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pep8.py 81KB

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