46
46
700 statements
47
47
900 syntax error
48
48
"""
49
- from __future__ import with_statement
50
-
51
49
import bisect
52
50
import inspect
53
51
import keyword
@@ -122,14 +120,11 @@ def lru_cache(maxsize=128): # noqa as it's a fake implementation.
122
120
UNARY_OPERATORS = frozenset (['>>' , '**' , '*' , '+' , '-' ])
123
121
ARITHMETIC_OP = frozenset (['**' , '*' , '/' , '//' , '+' , '-' , '@' ])
124
122
WS_OPTIONAL_OPERATORS = ARITHMETIC_OP .union (['^' , '&' , '|' , '<<' , '>>' , '%' ])
125
- # Warn for -> function annotation operator in py3.5+ (issue 803)
126
- FUNCTION_RETURN_ANNOTATION_OP = ['->' ] if sys .version_info >= (3 , 5 ) else []
127
123
ASSIGNMENT_EXPRESSION_OP = [':=' ] if sys .version_info >= (3 , 8 ) else []
128
124
WS_NEEDED_OPERATORS = frozenset ([
129
125
'**=' , '*=' , '/=' , '//=' , '+=' , '-=' , '!=' , '<>' , '<' , '>' ,
130
126
'%=' , '^=' , '&=' , '|=' , '==' , '<=' , '>=' , '<<=' , '>>=' , '=' ,
131
- 'and' , 'in' , 'is' , 'or' ] +
132
- FUNCTION_RETURN_ANNOTATION_OP +
127
+ 'and' , 'in' , 'is' , 'or' , '->' ] +
133
128
ASSIGNMENT_EXPRESSION_OP )
134
129
WHITESPACE = frozenset (' \t ' )
135
130
NEWLINE = frozenset ([tokenize .NL , tokenize .NEWLINE ])
@@ -158,7 +153,7 @@ def lru_cache(maxsize=128): # noqa as it's a fake implementation.
158
153
STARTSWITH_DEF_REGEX = re .compile (r'^(async\s+def|def)\b' )
159
154
STARTSWITH_TOP_LEVEL_REGEX = re .compile (r'^(async\s+def\s+|def\s+|class\s+|@)' )
160
155
STARTSWITH_INDENT_STATEMENT_REGEX = re .compile (
161
- r'^\s*({0 })\b' .format ('|' .join (s .replace (' ' , r'\s+' ) for s in (
156
+ r'^\s*({})\b' .format ('|' .join (s .replace (' ' , r'\s+' ) for s in (
162
157
'def' , 'async def' ,
163
158
'for' , 'async for' ,
164
159
'if' , 'elif' , 'else' ,
@@ -175,13 +170,10 @@ def lru_cache(maxsize=128): # noqa as it's a fake implementation.
175
170
176
171
177
172
def _get_parameters (function ):
178
- if sys .version_info >= (3 , 3 ):
179
- return [parameter .name
180
- for parameter
181
- in inspect .signature (function ).parameters .values ()
182
- if parameter .kind == parameter .POSITIONAL_OR_KEYWORD ]
183
- else :
184
- return inspect .getargspec (function )[0 ]
173
+ return [parameter .name
174
+ for parameter
175
+ in inspect .signature (function ).parameters .values ()
176
+ if parameter .kind == parameter .POSITIONAL_OR_KEYWORD ]
185
177
186
178
187
179
def register_check (check , codes = None ):
@@ -429,8 +421,8 @@ def blank_lines(logical_line, blank_lines, indent_level, line_number,
429
421
yield 0 , "E306 expected %s blank line before a " \
430
422
"nested definition, found 0" % (method_lines ,)
431
423
else :
432
- yield 0 , "E301 expected %s blank line, found 0" % (
433
- method_lines , )
424
+ yield 0 , "E301 expected {} blank line, found 0" . format (
425
+ method_lines )
434
426
elif blank_before != top_level_lines :
435
427
yield 0 , "E302 expected %s blank lines, found %d" % (
436
428
top_level_lines , blank_before )
@@ -474,7 +466,7 @@ def extraneous_whitespace(logical_line):
474
466
yield found + 1 , "E201 whitespace after '%s'" % char
475
467
elif line [found - 1 ] != ',' :
476
468
code = ('E202' if char in '}])' else 'E203' ) # if char in ',;:'
477
- yield found , "%s whitespace before '%s'" % ( code , char )
469
+ yield found , f" { code } whitespace before '{ char } '"
478
470
479
471
480
472
@register_check
@@ -735,7 +727,7 @@ def continued_indentation(logical_line, tokens, indent_level, hang_closing,
735
727
indent [depth ] = start [1 ]
736
728
indent_chances [start [1 ]] = True
737
729
if verbose >= 4 :
738
- print ("bracket depth %s indent to %s" % ( depth , start [1 ]) )
730
+ print (f "bracket depth { depth } indent to { start [1 ]} " )
739
731
# deal with implicit string concatenation
740
732
elif (token_type in (tokenize .STRING , tokenize .COMMENT ) or
741
733
text in ('u' , 'ur' , 'b' , 'br' )):
@@ -1228,7 +1220,7 @@ def compound_statements(logical_line):
1228
1220
lambda_kw = LAMBDA_REGEX .search (line , 0 , found )
1229
1221
if lambda_kw :
1230
1222
before = line [:lambda_kw .start ()].rstrip ()
1231
- if before [- 1 :] == '=' and isidentifier ( before [:- 1 ].strip ()):
1223
+ if before [- 1 :] == '=' and before [:- 1 ].strip (). isidentifier ( ):
1232
1224
yield 0 , ("E731 do not assign a lambda expression, use a "
1233
1225
"def" )
1234
1226
break
@@ -1473,7 +1465,7 @@ def comparison_type(logical_line, noqa):
1473
1465
match = COMPARE_TYPE_REGEX .search (logical_line )
1474
1466
if match and not noqa :
1475
1467
inst = match .group (1 )
1476
- if inst and isidentifier (inst ) and inst not in SINGLETONS :
1468
+ if inst and inst . isidentifier () and inst not in SINGLETONS :
1477
1469
return # Allow comparison for types which are not obvious
1478
1470
yield match .start (), "E721 do not compare types, use 'isinstance()'"
1479
1471
@@ -1822,30 +1814,21 @@ def maximum_doc_length(logical_line, max_doc_length, noqa, tokens):
1822
1814
########################################################################
1823
1815
1824
1816
1825
- if sys .version_info < (3 ,):
1826
- # Python 2: implicit encoding.
1827
- def readlines (filename ):
1828
- """Read the source code."""
1829
- with open (filename , 'rU' ) as f :
1817
+ def readlines (filename ):
1818
+ """Read the source code."""
1819
+ try :
1820
+ with tokenize .open (filename ) as f :
1821
+ return f .readlines ()
1822
+ except (LookupError , SyntaxError , UnicodeError ):
1823
+ # Fall back if file encoding is improperly declared
1824
+ with open (filename , encoding = 'latin-1' ) as f :
1830
1825
return f .readlines ()
1831
- isidentifier = re .compile (r'[a-zA-Z_]\w*$' ).match
1832
- stdin_get_value = sys .stdin .read
1833
- else :
1834
- # Python 3
1835
- def readlines (filename ):
1836
- """Read the source code."""
1837
- try :
1838
- with tokenize .open (filename ) as f :
1839
- return f .readlines ()
1840
- except (LookupError , SyntaxError , UnicodeError ):
1841
- # Fall back if file encoding is improperly declared
1842
- with open (filename , encoding = 'latin-1' ) as f :
1843
- return f .readlines ()
1844
- isidentifier = str .isidentifier
1845
-
1846
- def stdin_get_value ():
1847
- """Read the value from stdin."""
1848
- return TextIOWrapper (sys .stdin .buffer , errors = 'ignore' ).read ()
1826
+
1827
+
1828
+ def stdin_get_value ():
1829
+ """Read the value from stdin."""
1830
+ return TextIOWrapper (sys .stdin .buffer , errors = 'ignore' ).read ()
1831
+
1849
1832
1850
1833
noqa = lru_cache (512 )(re .compile (r'# no(?:qa|pep8)\b' , re .I ).search )
1851
1834
@@ -1911,7 +1894,7 @@ def parse_udiff(diff, patterns=None, parent='.'):
1911
1894
continue
1912
1895
if line [:3 ] == '@@ ' :
1913
1896
hunk_match = HUNK_REGEX .match (line )
1914
- (row , nrows ) = [ int (g or '1' ) for g in hunk_match .groups ()]
1897
+ (row , nrows ) = ( int (g or '1' ) for g in hunk_match .groups ())
1915
1898
rv [path ].update (range (row , row + nrows ))
1916
1899
elif line [:3 ] == '+++' :
1917
1900
path = line [4 :].split ('\t ' , 1 )[0 ]
@@ -1972,7 +1955,7 @@ def _is_eol_token(token):
1972
1955
########################################################################
1973
1956
1974
1957
1975
- class Checker ( object ) :
1958
+ class Checker :
1976
1959
"""Load a Python source file, tokenize it, check coding style."""
1977
1960
1978
1961
def __init__ (self , filename = None , lines = None ,
@@ -2004,9 +1987,9 @@ def __init__(self, filename=None, lines=None,
2004
1987
elif lines is None :
2005
1988
try :
2006
1989
self .lines = readlines (filename )
2007
- except IOError :
1990
+ except OSError :
2008
1991
(exc_type , exc ) = sys .exc_info ()[:2 ]
2009
- self ._io_error = '%s: %s' % ( exc_type .__name__ , exc )
1992
+ self ._io_error = f' { exc_type .__name__ } : { exc } '
2010
1993
self .lines = []
2011
1994
else :
2012
1995
self .lines = lines
@@ -2031,7 +2014,7 @@ def report_invalid_syntax(self):
2031
2014
else :
2032
2015
offset = (1 , 0 )
2033
2016
self .report_error (offset [0 ], offset [1 ] or 0 ,
2034
- 'E901 %s: %s' % ( exc_type .__name__ , exc .args [0 ]) ,
2017
+ f 'E901 { exc_type .__name__ } : { exc .args [0 ]} ' ,
2035
2018
self .report_invalid_syntax )
2036
2019
2037
2020
def readline (self ):
@@ -2224,7 +2207,7 @@ def check_all(self, expected=None, line_offset=0):
2224
2207
token_type , text = token [0 :2 ]
2225
2208
if self .verbose >= 3 :
2226
2209
if token [2 ][0 ] == token [3 ][0 ]:
2227
- pos = '[%s:%s]' % (token [2 ][1 ] or '' , token [3 ][1 ])
2210
+ pos = '[{}:{}]' . format (token [2 ][1 ] or '' , token [3 ][1 ])
2228
2211
else :
2229
2212
pos = 'l.%s' % token [3 ][0 ]
2230
2213
print ('l.%s\t %s\t %s\t %r' %
@@ -2251,7 +2234,7 @@ def check_all(self, expected=None, line_offset=0):
2251
2234
return self .report .get_file_results ()
2252
2235
2253
2236
2254
- class BaseReport ( object ) :
2237
+ class BaseReport :
2255
2238
"""Collect the results of the checks."""
2256
2239
2257
2240
print_filename = False
@@ -2333,7 +2316,7 @@ def print_statistics(self, prefix=''):
2333
2316
2334
2317
def print_benchmark (self ):
2335
2318
"""Print benchmark numbers."""
2336
- print ('%- 7.2f %s' % (self .elapsed , 'seconds elapsed' ))
2319
+ print ('{:< 7.2f} {}' . format (self .elapsed , 'seconds elapsed' ))
2337
2320
if self .elapsed :
2338
2321
for key in self ._benchmark_keys :
2339
2322
print ('%-7d %s per second (%d total)' %
@@ -2351,7 +2334,7 @@ class StandardReport(BaseReport):
2351
2334
"""Collect and print the results of the checks."""
2352
2335
2353
2336
def __init__ (self , options ):
2354
- super (StandardReport , self ).__init__ (options )
2337
+ super ().__init__ (options )
2355
2338
self ._fmt = REPORT_FORMAT .get (options .format .lower (),
2356
2339
options .format )
2357
2340
self ._repeat = options .repeat
@@ -2361,13 +2344,12 @@ def __init__(self, options):
2361
2344
def init_file (self , filename , lines , expected , line_offset ):
2362
2345
"""Signal a new file."""
2363
2346
self ._deferred_print = []
2364
- return super (StandardReport , self ).init_file (
2347
+ return super ().init_file (
2365
2348
filename , lines , expected , line_offset )
2366
2349
2367
2350
def error (self , line_number , offset , text , check ):
2368
2351
"""Report an error, according to options."""
2369
- code = super (StandardReport , self ).error (line_number , offset ,
2370
- text , check )
2352
+ code = super ().error (line_number , offset , text , check )
2371
2353
if code and (self .counters [code ] == 1 or self ._repeat ):
2372
2354
self ._deferred_print .append (
2373
2355
(line_number , offset , code , text [5 :], check .__doc__ ))
@@ -2406,16 +2388,16 @@ class DiffReport(StandardReport):
2406
2388
"""Collect and print the results for the changed lines only."""
2407
2389
2408
2390
def __init__ (self , options ):
2409
- super (DiffReport , self ).__init__ (options )
2391
+ super ().__init__ (options )
2410
2392
self ._selected = options .selected_lines
2411
2393
2412
2394
def error (self , line_number , offset , text , check ):
2413
2395
if line_number not in self ._selected [self .filename ]:
2414
2396
return
2415
- return super (DiffReport , self ).error (line_number , offset , text , check )
2397
+ return super ().error (line_number , offset , text , check )
2416
2398
2417
2399
2418
- class StyleGuide ( object ) :
2400
+ class StyleGuide :
2419
2401
"""Initialize a PEP-8 instance with few options."""
2420
2402
2421
2403
def __init__ (self , * args , ** kwargs ):
@@ -2505,8 +2487,10 @@ def input_dir(self, dirname):
2505
2487
dirs .remove (subdir )
2506
2488
for filename in sorted (files ):
2507
2489
# contain a pattern that matches?
2508
- if ((filename_match (filename , filepatterns ) and
2509
- not self .excluded (filename , root ))):
2490
+ if (
2491
+ filename_match (filename , filepatterns ) and
2492
+ not self .excluded (filename , root )
2493
+ ):
2510
2494
runner (os .path .join (root , filename ))
2511
2495
2512
2496
def excluded (self , filename , parent = None ):
@@ -2676,8 +2660,8 @@ def read_config(options, args, arglist, parser):
2676
2660
print (" unknown option '%s' ignored" % opt )
2677
2661
continue
2678
2662
if options .verbose > 1 :
2679
- print (" %s = %s" % (opt ,
2680
- config .get (pycodestyle_section , opt )))
2663
+ print (" {} = {}" . format (opt ,
2664
+ config .get (pycodestyle_section , opt )))
2681
2665
normalized_opt = opt .replace ('-' , '_' )
2682
2666
opt_type = option_list [normalized_opt ]
2683
2667
if opt_type in ('int' , 'count' ):
0 commit comments