pycodestyle.py 99 KB

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