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

pycodestyle.py 94KB

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