Skip to content

Commit 00d73a3

Browse files
committed
Get things linting again.
Linted against pylint 3.11 with the pylintrc file recommended from the Google Python Style Guide, specifically from https://github.com/google/styleguide/blob/28d10d1/pylintrc. Then ran through `ruff check` as well.
1 parent a448682 commit 00d73a3

File tree

9 files changed

+134
-163
lines changed

9 files changed

+134
-163
lines changed

benchmarks/run.py

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,23 +19,18 @@
1919
import sys
2020
import time
2121

22-
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
23-
REPO_DIR = os.path.dirname(THIS_DIR)
24-
if not REPO_DIR in sys.path:
25-
sys.path.insert(0, REPO_DIR)
26-
27-
import json5 # pylint: disable=wrong-import-position
28-
22+
import json5
2923

3024
ALL_BENCHMARKS = (
3125
'64KB-min.json',
3226
'bitly-usa-gov.json',
3327
'twitter.json',
3428
)
3529

36-
3730
DEFAULT_ITERATIONS = 3
3831

32+
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
33+
3934

4035
def main():
4136
parser = argparse.ArgumentParser()
@@ -49,7 +44,7 @@ def main():
4944

5045
file_contents = []
5146
for f in args.benchmarks:
52-
with open(f) as fp:
47+
with open(f, encoding='utf-8') as fp:
5348
file_contents.append(fp.read())
5449

5550

@@ -86,20 +81,20 @@ def py_maker(*args, **kwargs):
8681
if json5_time and json_time:
8782
if json5_time > json_time:
8883
avg = json5_time / json_time
89-
print("%-20s: JSON was %5.1fx faster (%.6fs to %.6fs)" % (
90-
fname, avg, json_time, json5_time))
84+
print(f"{fname:-%20s}: JSON was {avg:5.1f}x faster "
85+
f"({json_time:.6f} to {json5_time:.6fs}")
9186
else:
9287
avg = json_time / json5_time
93-
print("%-20s: JSON5 was %5.1fx faster (%.6fs to %.6fs)" % (
94-
fname, avg, json5_time, json_time))
88+
print(f"{fname:-%20s}: JSON5 was {avg:5.1f}x faster "
89+
f"({json5_time:.6f} to {json_time:.6fs}")
9590
elif json5_time:
96-
print("%-20s: JSON5 took %.6f secs, JSON was too fast to measure" %
97-
(fname, json5_time))
91+
print(f"{fname:-20s}: JSON5 took {json5_time:.6f} secs, "
92+
f"JSON was too fast to measure")
9893
elif json_time:
99-
print("%-20s: JSON took %.6f secs, JSON5 was too fast to measure" %
100-
(fname, json_time))
94+
print(f"{fname:-20s}: JSON took {json_time:.6f} secs, "
95+
f"JSON5 was too fast to measure")
10196
else:
102-
print("%-20s: both were too fast to measure" % (fname,))
97+
print(f"{fname:-20s}: both were too fast to measure")
10398

10499
return 0
105100

json5/arg_parser.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,18 +40,16 @@ def parse_args(self, args=None, namespace=None):
4040

4141
return rargs
4242

43-
# Redefining built-in 'file' pylint: disable=W0622
44-
45-
def _print_message(self, msg, file=None):
46-
self._host.print_(msg=msg, stream=file, end='\n')
43+
def _print_message(self, message, file=None):
44+
self._host.print_(msg=message, stream=file, end='\n')
4745

4846
def print_help(self, file=None):
49-
self._print_message(msg=self.format_help(), file=file)
47+
self._print_message(message=self.format_help(), file=file)
5048

51-
def error(self, message, bailout=True): # pylint: disable=W0221
52-
self.exit(2, '%s: error: %s\n' % (self.prog, message), bailout=bailout)
49+
def error(self, message, bailout=True):
50+
self.exit(2, f'{self.prog}: error: {message}\n', bailout=bailout)
5351

54-
def exit(self, status=0, message=None, # pylint: disable=W0221
52+
def exit(self, status=0, message=None,
5553
bailout=True):
5654
self.exit_status = status
5755
if message:

json5/lib.py

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import math
1616
import re
1717
from typing import Any, Callable, IO, Iterable, Mapping, Optional, \
18-
Sequence, Set, Tuple, Union
18+
Set, Tuple, Union
1919
import unicodedata
2020

2121
from .parser import Parser
@@ -92,13 +92,15 @@ def _fp_constant_parser(s):
9292
if object_pairs_hook:
9393
dictify = object_pairs_hook
9494
elif object_hook:
95-
dictify = lambda pairs: object_hook(dict(pairs))
95+
def dictify(pairs):
96+
return object_hook(dict(pairs))
9697
else:
97-
dictify = lambda pairs: dict(pairs) # pylint: disable=unnecessary-lambda
98+
dictify = dict
9899

99100
if not allow_duplicate_keys:
100101
_orig_dictify = dictify
101-
dictify = lambda pairs: _reject_duplicate_keys(pairs, _orig_dictify)
102+
def dictify(pairs):
103+
return _reject_duplicate_keys(pairs, _orig_dictify)
102104

103105
parse_float = parse_float or float
104106
parse_int = parse_int or int
@@ -111,7 +113,7 @@ def _reject_duplicate_keys(pairs, dictify):
111113
keys = set()
112114
for key, _ in pairs:
113115
if key in keys:
114-
raise ValueError('Duplicate key "%s" found in object', key)
116+
raise ValueError(f'Duplicate key "{key}" found in object')
115117
keys.add(key)
116118
return dictify(pairs)
117119

@@ -129,12 +131,11 @@ def _walk_ast(el,
129131
if ty == 'number':
130132
if v.startswith('0x') or v.startswith('0X'):
131133
return parse_int(v, base=16)
132-
elif '.' in v or 'e' in v or 'E' in v:
134+
if '.' in v or 'e' in v or 'E' in v:
133135
return parse_float(v)
134-
elif 'Infinity' in v or 'NaN' in v:
136+
if 'Infinity' in v or 'NaN' in v:
135137
return parse_constant(v)
136-
else:
137-
return parse_int(v)
138+
return parse_int(v)
138139
if ty == 'string':
139140
return v
140141
if ty == 'object':
@@ -147,7 +148,7 @@ def _walk_ast(el,
147148
if ty == 'array':
148149
return [_walk_ast(el, dictify, parse_float, parse_int, parse_constant)
149150
for el in v]
150-
raise Exception('unknown el: ' + el) # pragma: no cover
151+
raise ValueError('unknown el: ' + el) # pragma: no cover
151152

152153

153154
def dump(obj: Any,
@@ -202,6 +203,7 @@ def dump(obj: Any,
202203
should produce exactly the same output as ``json.dump(obj, fp).``
203204
"""
204205

206+
del kwargs
205207
fp.write(dumps(obj=obj, skipkeys=skipkeys, ensure_ascii=ensure_ascii,
206208
check_circular=check_circular, allow_nan=allow_nan,
207209
cls=cls, indent=indent, separators=separators,
@@ -261,6 +263,7 @@ def dumps(obj: Any,
261263
"""
262264

263265
assert kwargs.get('cls', None) is None, 'Custom encoders are not supported'
266+
del cls
264267

265268
if separators is None:
266269
if indent is None:
@@ -291,6 +294,7 @@ def _dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, indent,
291294
seen: Optional[Set[int]],
292295
level: int,
293296
is_key: bool):
297+
# pylint: disable=too-many-statements
294298
if obj is True:
295299
s = 'true'
296300
elif obj is False:
@@ -332,10 +336,10 @@ def _dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, indent,
332336

333337
if is_key:
334338
if s is not None:
335-
return True, '"%s"' % s
339+
return True, f'"{s}"'
336340
if skipkeys:
337341
return False, None
338-
raise TypeError('invalid key %s' % repr(obj))
342+
raise TypeError(f'invalid key {repr(obj)}')
339343

340344
if s is not None:
341345
return True, s
@@ -344,7 +348,7 @@ def _dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, indent,
344348
end_str = ''
345349
if trailing_commas:
346350
end_str = ','
347-
if type(indent) == int:
351+
if isinstance(indent, int):
348352
if indent > 0:
349353
indent_str = '\n' + ' ' * indent * level
350354
end_str += '\n' + ' ' * indent * (level - 1)
@@ -365,11 +369,11 @@ def _dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, indent,
365369
i = id(obj)
366370
if i in seen:
367371
raise ValueError('Circular reference detected.')
368-
else:
369-
seen.add(i)
372+
seen.add(i)
370373

371-
# In Python3, we'd check if this was an abc.Mapping or an abc.Sequence.
372-
# For now, just check for the attrs we need to iterate over the object.
374+
# Ideally we'd use collections.abc.Mapping and collections.abc.Sequence
375+
# here, but for backwards-compatibility with potential old callers,
376+
# we only check for the two attributes we need in each case.
373377
if hasattr(obj, 'keys') and hasattr(obj, '__getitem__'):
374378
s = _dump_dict(obj, skipkeys, ensure_ascii,
375379
check_circular, allow_nan, indent,
@@ -423,9 +427,8 @@ def _dump_dict(obj, skipkeys, ensure_ascii, check_circular, allow_nan,
423427
if valid_key:
424428
if not allow_duplicate_keys:
425429
if key_str in new_keys:
426-
raise ValueError('duplicate key %s' % repr(key))
427-
else:
428-
new_keys.add(key_str)
430+
raise ValueError(f'duplicate key {repr(key)}')
431+
new_keys.add(key_str)
429432
if num_items_added:
430433
s += item_sep
431434
s += key_str + kv_sep + _dumps(obj[key], skipkeys, ensure_ascii,
@@ -436,7 +439,7 @@ def _dump_dict(obj, skipkeys, ensure_ascii, check_circular, allow_nan,
436439
seen, level, is_key=False)[1]
437440
num_items_added += 1
438441
elif not skipkeys:
439-
raise TypeError('invalid key %s' % repr(key))
442+
raise TypeError(f'invalid key {repr(key)}')
440443

441444
s += end_str + '}'
442445
return s
@@ -486,15 +489,15 @@ def _dump_str(obj, ensure_ascii):
486489
ret.append(ch)
487490
else:
488491
o = ord(ch)
489-
if o >= 32 and o < 128:
492+
if 32 <= o < 128:
490493
ret.append(ch)
491494
elif o < 65536:
492-
ret.append('\\u' + '%04x' % o)
495+
ret.append(f'\\u{o:04x}')
493496
else:
494497
val = o - 0x10000
495498
high = 0xd800 + (val >> 10)
496499
low = 0xdc00 + (val & 0x3ff)
497-
ret.append('\\u%04x\\u%04x' % (high, low))
500+
ret.append(f'\\u{high:04x}\\u{low:04x}')
498501
return ''.join(ret) + '"'
499502

500503

@@ -566,4 +569,4 @@ def _is_reserved_word(k):
566569

567570

568571
def _raise_type_error(obj):
569-
raise TypeError('%s is not JSON5 serializable' % repr(obj))
572+
raise TypeError(f'{repr(obj)} is not JSON5 serializable')

json5/parser.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
# pylint: disable=line-too-long,unnecessary-lambda
1+
# pylint: disable=line-too-long,too-many-lines,unnecessary-lambda
2+
3+
import unicodedata
24

35

46
class Parser:
@@ -24,9 +26,8 @@ def _err_str(self):
2426
if self.errpos == len(self.msg):
2527
thing = 'end of input'
2628
else:
27-
thing = '"%s"' % self.msg[self.errpos]
28-
return '%s:%d Unexpected %s at column %d' % (
29-
self.fname, lineno, thing, colno)
29+
thing = f'"{self.msg[self.errpos]}"'
30+
return f'{self.fname}:{lineno} Unexpected {thing} at column {colno}'
3031

3132
def _err_offsets(self):
3233
lineno = 1
@@ -48,8 +49,7 @@ def _succeed(self, v, newpos=None):
4849
def _fail(self):
4950
self.val = None
5051
self.failed = True
51-
if self.pos >= self.errpos:
52-
self.errpos = self.pos
52+
self.errpos = max(self.errpos, self.pos)
5353

5454
def _rewind(self, newpos):
5555
self._succeed(None, newpos)
@@ -94,8 +94,7 @@ def _star(self, rule, vs=None):
9494
if self.failed:
9595
self._rewind(p)
9696
break
97-
else:
98-
vs.append(self.val)
97+
vs.append(self.val)
9998
self._succeed(vs)
10099

101100
def _seq(self, rules):
@@ -148,7 +147,6 @@ def _set(self, var, val):
148147
self._scopes[-1][1][var] = val
149148

150149
def _is_unicat(self, var, cat):
151-
import unicodedata
152150
return unicodedata.category(var) == cat
153151

154152
def _join(self, s, vs):
@@ -199,7 +197,7 @@ def _ws__c8__s0_(self):
199197
self._not(lambda: self._not(self._ws__c8__s0_n_n_))
200198

201199
def _ws__c8__s0_n_n_(self):
202-
(lambda: self._choose([self._ws__c8__s0_n_n_g__c0_]))()
200+
self._choose([self._ws__c8__s0_n_n_g__c0_])
203201

204202
def _ws__c8__s0_n_n_g__c0_(self):
205203
self._seq([lambda: self._bind(self._anything_, 'x'),

pylintrc

Lines changed: 0 additions & 57 deletions
This file was deleted.

pyproject.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,12 @@ dev = ["hypothesis"]
3535
[project.scripts]
3636
pyjson5 = "json5.tool:main"
3737

38+
[tool.ruff]
39+
include = [ "run", "*/*.py" ]
40+
line-length = 79
41+
42+
[tool.ruff.format]
43+
quote-style = "single"
44+
3845
[tool.setuptools.dynamic]
3946
version = {attr = "json5.__version__"}

0 commit comments

Comments
 (0)