Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

pycodestyle.py 100KB

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