pycodestyle.py 97 KB

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