Skip to content

Commit df79a63

Browse files
authored
refactor: remove redundant Python 2 code (#1155)
* Remove Python 2 code * Upgrade Python syntax with pyupgrade * Upgrade Python syntax with pyupgrade --py3-plus * Upgrade Python syntax with pyupgrade --py36-plus * Remove unused imports
1 parent bb73791 commit df79a63

13 files changed

+61
-78
lines changed

coverage/fullcoverage/encodings.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
import sys
2020

21-
class FullCoverageTracer(object):
21+
class FullCoverageTracer:
2222
def __init__(self):
2323
# `traces` is a list of trace events. Frames are tricky: the same
2424
# frame object is used for a whole scope, with new line numbers

doc/conf.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
32
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
43

@@ -58,8 +57,8 @@
5857
master_doc = 'index'
5958

6059
# General information about the project.
61-
project = u'Coverage.py'
62-
copyright = u'2009\N{EN DASH}2021, Ned Batchelder.' # CHANGEME # pylint: disable=redefined-builtin
60+
project = 'Coverage.py'
61+
copyright = '2009\N{EN DASH}2021, Ned Batchelder.' # CHANGEME # pylint: disable=redefined-builtin
6362

6463
# The version info for the project you're documenting, acts as replacement for
6564
# |version| and |release|, also used in various other places throughout the
@@ -229,7 +228,7 @@
229228
r"https://github.com/nedbat/coveragepy/(issues|pull)/\d+",
230229
# When publishing a new version, the docs will refer to the version before
231230
# the docs have been published. So don't check those links.
232-
r"https://coverage.readthedocs.io/en/{}$".format(release),
231+
fr"https://coverage.readthedocs.io/en/{release}$",
233232
]
234233

235234
# https://github.com/executablebooks/sphinx-tabs/pull/54

lab/disgen.py

-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
# instead of printing to stdout.
55

66
import sys
7-
import types
87
import collections
98

109
from opcode import *

lab/find_class.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
class Parent(object):
1+
class Parent:
22
def meth(self):
33
print("METH")
44

@@ -31,7 +31,7 @@ def trace(frame, event, args):
3131
if f is func:
3232
qname = cls.__name__ + "." + fname
3333
break
34-
print("{}: {}.{} {}".format(event, self, fname, qname))
34+
print(f"{event}: {self}.{fname} {qname}")
3535
return trace
3636

3737
import sys

lab/genpy.py

+11-13
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,11 @@
44
from itertools import cycle, product
55
import random
66
import re
7-
import sys
87

9-
import coverage
108
from coverage.parser import PythonParser
119

1210

13-
class PythonSpinner(object):
11+
class PythonSpinner:
1412
"""Spin Python source from a simple AST."""
1513

1614
def __init__(self):
@@ -29,7 +27,7 @@ def generate_python(cls, ast):
2927
return "\n".join(spinner.lines)
3028

3129
def add_line(self, line):
32-
g = "g{}".format(self.lineno)
30+
g = f"g{self.lineno}"
3331
self.lines.append(' ' * self.indent + line.format(g=g, lineno=self.lineno))
3432

3533
def add_block(self, node):
@@ -65,15 +63,15 @@ def gen_python_internal(self, ast):
6563
# number.
6664
if len(node) > 2 and node[2] is not None:
6765
for except_node in node[2]:
68-
self.add_line("except Exception{}:".format(self.lineno))
66+
self.add_line(f"except Exception{self.lineno}:")
6967
self.add_block(except_node)
7068
self.maybe_block(node, 3, "else")
7169
self.maybe_block(node, 4, "finally")
7270
elif op == "with":
7371
self.add_line("with {g} as x:")
7472
self.add_block(node[1])
7573
else:
76-
raise Exception("Bad list node: {!r}".format(node))
74+
raise Exception(f"Bad list node: {node!r}")
7775
else:
7876
op = node
7977
if op == "assign":
@@ -85,7 +83,7 @@ def gen_python_internal(self, ast):
8583
elif op == "yield":
8684
self.add_line("yield {lineno}")
8785
else:
88-
raise Exception("Bad atom node: {!r}".format(node))
86+
raise Exception(f"Bad atom node: {node!r}")
8987

9088

9189
def weighted_choice(rand, choices):
@@ -100,7 +98,7 @@ def weighted_choice(rand, choices):
10098
assert False, "Shouldn't get here"
10199

102100

103-
class RandomAstMaker(object):
101+
class RandomAstMaker:
104102
def __init__(self, seed=None):
105103
self.r = random.Random()
106104
if seed is not None:
@@ -139,22 +137,22 @@ def make_body(self, parent):
139137
body[-1].append(self.make_body("ifelse"))
140138
elif stmt == "for":
141139
old_allowed = self.bc_allowed
142-
self.bc_allowed = self.bc_allowed | set(["break", "continue"])
140+
self.bc_allowed = self.bc_allowed | {"break", "continue"}
143141
body.append(["for", self.make_body("for")])
144142
self.bc_allowed = old_allowed
145143
if self.roll():
146144
body[-1].append(self.make_body("forelse"))
147145
elif stmt == "while":
148146
old_allowed = self.bc_allowed
149-
self.bc_allowed = self.bc_allowed | set(["break", "continue"])
147+
self.bc_allowed = self.bc_allowed | {"break", "continue"}
150148
body.append(["while", self.make_body("while")])
151149
self.bc_allowed = old_allowed
152150
if self.roll():
153151
body[-1].append(self.make_body("whileelse"))
154152
elif stmt == "try":
155153
else_clause = self.make_body("try") if self.roll() else None
156154
old_allowed = self.bc_allowed
157-
self.bc_allowed = self.bc_allowed - set(["continue"])
155+
self.bc_allowed = self.bc_allowed - {"continue"}
158156
finally_clause = self.make_body("finally") if self.roll() else None
159157
self.bc_allowed = old_allowed
160158
if else_clause:
@@ -235,7 +233,7 @@ def show_a_bunch():
235233
print("-"*80, "\n", source, sep="")
236234
compile(source, "<string>", "exec")
237235
except Exception as ex:
238-
print("Oops: {}\n{}".format(ex, source))
236+
print(f"Oops: {ex}\n{source}")
239237
if len(source) > len(longest):
240238
longest = source
241239

@@ -248,7 +246,7 @@ def show_alternatives():
248246
if nlines < 15:
249247
nalt = compare_alternatives(source)
250248
if nalt > 1:
251-
print("--- {:3} lines, {:2} alternatives ---------".format(nlines, nalt))
249+
print(f"--- {nlines:3} lines, {nalt:2} alternatives ---------")
252250
print(source)
253251

254252

lab/parse_all.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,16 @@
33
import os
44
import sys
55

6-
from coverage.exceptions import CoverageException
76
from coverage.parser import PythonParser
87

98
for root, dirnames, filenames in os.walk(sys.argv[1]):
109
for filename in filenames:
1110
if filename.endswith(".py"):
1211
filename = os.path.join(root, filename)
13-
print(":: {}".format(filename))
12+
print(f":: {filename}")
1413
try:
1514
par = PythonParser(filename=filename)
1615
par.parse_source()
1716
par.arcs()
1817
except Exception as exc:
19-
print(" ** {}".format(exc))
18+
print(f" ** {exc}")

lab/parser.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
"""Parser.py: a main for invoking code in coverage/parser.py"""
55

6-
from __future__ import division
76

87
import collections
98
import glob
@@ -21,7 +20,7 @@
2120
opcode_counts = collections.Counter()
2221

2322

24-
class ParserMain(object):
23+
class ParserMain:
2524
"""A main for code parsing experiments."""
2625

2726
def main(self, args):
@@ -65,9 +64,9 @@ def main(self, args):
6564

6665
if options.histogram:
6766
total = sum(opcode_counts.values())
68-
print("{} total opcodes".format(total))
67+
print(f"{total} total opcodes")
6968
for opcode, number in opcode_counts.most_common():
70-
print("{:20s} {:6d} {:.1%}".format(opcode, number, number/total))
69+
print(f"{opcode:20s} {number:6d} {number/total:.1%}")
7170

7271
def one_file(self, options, filename):
7372
"""Process just one file."""
@@ -89,7 +88,7 @@ def one_file(self, options, filename):
8988
pyparser = PythonParser(text, filename=filename, exclude=r"no\s*cover")
9089
pyparser.parse_source()
9190
except Exception as err:
92-
print("%s" % (err,))
91+
print(f"{err}")
9392
return
9493

9594
if options.dis:
@@ -151,12 +150,12 @@ def disassemble(self, byte_parser, histogram=False):
151150
if srclines:
152151
upto = upto or disline.lineno-1
153152
while upto <= disline.lineno-1:
154-
print("%100s%s" % ("", srclines[upto]))
153+
print("{:>100}{}".format("", srclines[upto]))
155154
upto += 1
156155
elif disline.offset > 0:
157156
print("")
158157
line = disgen.format_dis_line(disline)
159-
print("%-70s" % (line,))
158+
print(f"{line:<70}")
160159

161160
print("")
162161

@@ -211,7 +210,7 @@ def set_char(s, n, c):
211210

212211
def blanks(s):
213212
"""Return the set of positions where s is blank."""
214-
return set(i for i, c in enumerate(s) if c == " ")
213+
return {i for i, c in enumerate(s) if c == " "}
215214

216215

217216
def first_all_blanks(ss):

lab/platform_info.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@ def whatever(f):
1515

1616

1717
def dump_module(mod):
18-
print("\n### {} ---------------------------".format(mod.__name__))
18+
print(f"\n### {mod.__name__} ---------------------------")
1919
for name in dir(mod):
2020
if name.startswith("_"):
2121
continue
22-
print("{:30s}: {!r:.100}".format(name, whatever(getattr(mod, name))))
22+
print(f"{name:30s}: {whatever(getattr(mod, name))!r:.100}")
2323

2424

2525
for mod in [platform, sys]:

lab/show_platform.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,4 @@
1313
n += "()"
1414
except:
1515
continue
16-
print("%30s: %r" % (n, v))
16+
print(f"{n:>30}: {v!r}")

lab/show_pyc.py

+20-29
Original file line numberDiff line numberDiff line change
@@ -28,18 +28,16 @@ def show_pyc_file(fname):
2828
flags = struct.unpack('<L', f.read(4))[0]
2929
hash_based = flags & 0x01
3030
check_source = flags & 0x02
31-
print("flags 0x%08x" % (flags,))
31+
print(f"flags 0x{flags:08x}")
3232
if hash_based:
3333
source_hash = f.read(8)
3434
read_date_and_size = False
3535
if read_date_and_size:
3636
moddate = f.read(4)
3737
modtime = time.asctime(time.localtime(struct.unpack('<L', moddate)[0]))
38-
print("moddate %s (%s)" % (binascii.hexlify(moddate), modtime))
39-
if sys.version_info >= (3, 3):
40-
# 3.3 added another long to the header (size).
41-
size = f.read(4)
42-
print("pysize %s (%d)" % (binascii.hexlify(size), struct.unpack('<L', size)[0]))
38+
print(f"moddate {binascii.hexlify(moddate)} ({modtime})")
39+
size = f.read(4)
40+
print("pysize %s (%d)" % (binascii.hexlify(size), struct.unpack('<L', size)[0]))
4341
code = marshal.load(f)
4442
show_code(code)
4543

@@ -92,13 +90,13 @@ def show_code(code, indent='', number=None):
9290
label = ""
9391
if number is not None:
9492
label = "%d: " % number
95-
print("%s%scode" % (indent, label))
93+
print(f"{indent}{label}code")
9694
indent += " "
97-
print("%sname %r" % (indent, code.co_name))
95+
print(f"{indent}name {code.co_name!r}")
9896
print("%sargcount %d" % (indent, code.co_argcount))
9997
print("%snlocals %d" % (indent, code.co_nlocals))
10098
print("%sstacksize %d" % (indent, code.co_stacksize))
101-
print("%sflags %04x: %s" % (indent, code.co_flags, flag_words(code.co_flags, CO_FLAGS)))
99+
print(f"{indent}flags {code.co_flags:04x}: {flag_words(code.co_flags, CO_FLAGS)}")
102100
show_hex("code", code.co_code, indent=indent)
103101
dis.disassemble(code)
104102
print("%sconsts" % indent)
@@ -107,43 +105,36 @@ def show_code(code, indent='', number=None):
107105
show_code(const, indent+" ", number=i)
108106
else:
109107
print(" %s%d: %r" % (indent, i, const))
110-
print("%snames %r" % (indent, code.co_names))
111-
print("%svarnames %r" % (indent, code.co_varnames))
112-
print("%sfreevars %r" % (indent, code.co_freevars))
113-
print("%scellvars %r" % (indent, code.co_cellvars))
114-
print("%sfilename %r" % (indent, code.co_filename))
108+
print(f"{indent}names {code.co_names!r}")
109+
print(f"{indent}varnames {code.co_varnames!r}")
110+
print(f"{indent}freevars {code.co_freevars!r}")
111+
print(f"{indent}cellvars {code.co_cellvars!r}")
112+
print(f"{indent}filename {code.co_filename!r}")
115113
print("%sfirstlineno %d" % (indent, code.co_firstlineno))
116114
show_hex("lnotab", code.co_lnotab, indent=indent)
117-
print(" %s%s" % (indent, ", ".join("%r:%r" % (line, byte) for byte, line in lnotab_interpreted(code))))
115+
print(" {}{}".format(indent, ", ".join(f"{line!r}:{byte!r}" for byte, line in lnotab_interpreted(code))))
118116
if hasattr(code, "co_linetable"):
119117
show_hex("linetable", code.co_linetable, indent=indent)
120118
if hasattr(code, "co_lines"):
121-
print(" %sco_lines %s" % (
119+
print(" {}co_lines {}".format(
122120
indent,
123-
", ".join("%r:%r-%r" % (line, start, end) for start, end, line in code.co_lines())
121+
", ".join(f"{line!r}:{start!r}-{end!r}" for start, end, line in code.co_lines())
124122
))
125123

126124
def show_hex(label, h, indent):
127125
h = binascii.hexlify(h)
128126
if len(h) < 60:
129-
print("%s%s %s" % (indent, label, h.decode('ascii')))
127+
print("{}{} {}".format(indent, label, h.decode('ascii')))
130128
else:
131-
print("%s%s" % (indent, label))
129+
print(f"{indent}{label}")
132130
for i in range(0, len(h), 60):
133-
print("%s %s" % (indent, h[i:i+60].decode('ascii')))
131+
print("{} {}".format(indent, h[i:i+60].decode('ascii')))
134132

135-
if sys.version_info >= (3,):
136-
def bytes_to_ints(bytes_value):
137-
return bytes_value
138-
else:
139-
def bytes_to_ints(bytes_value):
140-
for byte in bytes_value:
141-
yield ord(byte)
142133

143134
def lnotab_interpreted(code):
144135
# Adapted from dis.py in the standard library.
145-
byte_increments = bytes_to_ints(code.co_lnotab[0::2])
146-
line_increments = bytes_to_ints(code.co_lnotab[1::2])
136+
byte_increments = code.co_lnotab[0::2]
137+
line_increments = code.co_lnotab[1::2]
147138

148139
last_line_num = None
149140
line_num = code.co_firstlineno

perf/bug397.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
Written by David MacIver as part of https://github.com/nedbat/coveragepy/issues/397
1111
1212
"""
13-
from __future__ import print_function
1413

1514
import sys
1615
import random
@@ -52,4 +51,4 @@ def sd(xs):
5251
for d in data:
5352
hash_str(d)
5453
timing.append(1000000 * (time.time() - start) / len(data))
55-
print("Runtime per example:", "%.2f +/- %.2f us" % (mean(timing), sd(timing)))
54+
print("Runtime per example:", f"{mean(timing):.2f} +/- {sd(timing):.2f} us")

0 commit comments

Comments
 (0)