pycodestyle.py 103 KB

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