summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHugo van Kemenade <hugovk@users.noreply.github.com>2021-05-03 01:40:05 +0300
committerGitHub <noreply@github.com>2021-05-02 15:40:05 -0700
commitdf79a6390f6d0531f6411f745d0ccd2c3d674883 (patch)
tree182575a9f279d791c9a3f724ed8373c750cb49bd
parentbb73791b59f74b6621a87036c14a6be6a23e0e55 (diff)
downloadpython-coveragepy-git-df79a6390f6d0531f6411f745d0ccd2c3d674883.tar.gz
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
-rw-r--r--coverage/fullcoverage/encodings.py2
-rw-r--r--doc/conf.py7
-rw-r--r--lab/disgen.py1
-rw-r--r--lab/find_class.py4
-rw-r--r--lab/genpy.py24
-rw-r--r--lab/parse_all.py5
-rw-r--r--lab/parser.py15
-rw-r--r--lab/platform_info.py4
-rw-r--r--lab/show_platform.py2
-rw-r--r--lab/show_pyc.py49
-rw-r--r--perf/bug397.py3
-rw-r--r--perf/perf_measure.py18
-rw-r--r--perf/solve_poly.py5
13 files changed, 61 insertions, 78 deletions
diff --git a/coverage/fullcoverage/encodings.py b/coverage/fullcoverage/encodings.py
index aeb416e4..b248bdbc 100644
--- a/coverage/fullcoverage/encodings.py
+++ b/coverage/fullcoverage/encodings.py
@@ -18,7 +18,7 @@ many of the most fundamental modules in the Standard Library.
import sys
-class FullCoverageTracer(object):
+class FullCoverageTracer:
def __init__(self):
# `traces` is a list of trace events. Frames are tricky: the same
# frame object is used for a whole scope, with new line numbers
diff --git a/doc/conf.py b/doc/conf.py
index 9d382c3d..3ebb02c6 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
@@ -58,8 +57,8 @@ source_suffix = '.rst'
master_doc = 'index'
# General information about the project.
-project = u'Coverage.py'
-copyright = u'2009\N{EN DASH}2021, Ned Batchelder.' # CHANGEME # pylint: disable=redefined-builtin
+project = 'Coverage.py'
+copyright = '2009\N{EN DASH}2021, Ned Batchelder.' # CHANGEME # pylint: disable=redefined-builtin
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -229,7 +228,7 @@ linkcheck_ignore = [
r"https://github.com/nedbat/coveragepy/(issues|pull)/\d+",
# When publishing a new version, the docs will refer to the version before
# the docs have been published. So don't check those links.
- r"https://coverage.readthedocs.io/en/{}$".format(release),
+ fr"https://coverage.readthedocs.io/en/{release}$",
]
# https://github.com/executablebooks/sphinx-tabs/pull/54
diff --git a/lab/disgen.py b/lab/disgen.py
index 26bc56bc..055f4983 100644
--- a/lab/disgen.py
+++ b/lab/disgen.py
@@ -4,7 +4,6 @@
# instead of printing to stdout.
import sys
-import types
import collections
from opcode import *
diff --git a/lab/find_class.py b/lab/find_class.py
index d8dac0b5..b8ab437b 100644
--- a/lab/find_class.py
+++ b/lab/find_class.py
@@ -1,4 +1,4 @@
-class Parent(object):
+class Parent:
def meth(self):
print("METH")
@@ -31,7 +31,7 @@ def trace(frame, event, args):
if f is func:
qname = cls.__name__ + "." + fname
break
- print("{}: {}.{} {}".format(event, self, fname, qname))
+ print(f"{event}: {self}.{fname} {qname}")
return trace
import sys
diff --git a/lab/genpy.py b/lab/genpy.py
index c0d91bc9..f968c916 100644
--- a/lab/genpy.py
+++ b/lab/genpy.py
@@ -4,13 +4,11 @@ import collections
from itertools import cycle, product
import random
import re
-import sys
-import coverage
from coverage.parser import PythonParser
-class PythonSpinner(object):
+class PythonSpinner:
"""Spin Python source from a simple AST."""
def __init__(self):
@@ -29,7 +27,7 @@ class PythonSpinner(object):
return "\n".join(spinner.lines)
def add_line(self, line):
- g = "g{}".format(self.lineno)
+ g = f"g{self.lineno}"
self.lines.append(' ' * self.indent + line.format(g=g, lineno=self.lineno))
def add_block(self, node):
@@ -65,7 +63,7 @@ class PythonSpinner(object):
# number.
if len(node) > 2 and node[2] is not None:
for except_node in node[2]:
- self.add_line("except Exception{}:".format(self.lineno))
+ self.add_line(f"except Exception{self.lineno}:")
self.add_block(except_node)
self.maybe_block(node, 3, "else")
self.maybe_block(node, 4, "finally")
@@ -73,7 +71,7 @@ class PythonSpinner(object):
self.add_line("with {g} as x:")
self.add_block(node[1])
else:
- raise Exception("Bad list node: {!r}".format(node))
+ raise Exception(f"Bad list node: {node!r}")
else:
op = node
if op == "assign":
@@ -85,7 +83,7 @@ class PythonSpinner(object):
elif op == "yield":
self.add_line("yield {lineno}")
else:
- raise Exception("Bad atom node: {!r}".format(node))
+ raise Exception(f"Bad atom node: {node!r}")
def weighted_choice(rand, choices):
@@ -100,7 +98,7 @@ def weighted_choice(rand, choices):
assert False, "Shouldn't get here"
-class RandomAstMaker(object):
+class RandomAstMaker:
def __init__(self, seed=None):
self.r = random.Random()
if seed is not None:
@@ -139,14 +137,14 @@ class RandomAstMaker(object):
body[-1].append(self.make_body("ifelse"))
elif stmt == "for":
old_allowed = self.bc_allowed
- self.bc_allowed = self.bc_allowed | set(["break", "continue"])
+ self.bc_allowed = self.bc_allowed | {"break", "continue"}
body.append(["for", self.make_body("for")])
self.bc_allowed = old_allowed
if self.roll():
body[-1].append(self.make_body("forelse"))
elif stmt == "while":
old_allowed = self.bc_allowed
- self.bc_allowed = self.bc_allowed | set(["break", "continue"])
+ self.bc_allowed = self.bc_allowed | {"break", "continue"}
body.append(["while", self.make_body("while")])
self.bc_allowed = old_allowed
if self.roll():
@@ -154,7 +152,7 @@ class RandomAstMaker(object):
elif stmt == "try":
else_clause = self.make_body("try") if self.roll() else None
old_allowed = self.bc_allowed
- self.bc_allowed = self.bc_allowed - set(["continue"])
+ self.bc_allowed = self.bc_allowed - {"continue"}
finally_clause = self.make_body("finally") if self.roll() else None
self.bc_allowed = old_allowed
if else_clause:
@@ -235,7 +233,7 @@ def show_a_bunch():
print("-"*80, "\n", source, sep="")
compile(source, "<string>", "exec")
except Exception as ex:
- print("Oops: {}\n{}".format(ex, source))
+ print(f"Oops: {ex}\n{source}")
if len(source) > len(longest):
longest = source
@@ -248,7 +246,7 @@ def show_alternatives():
if nlines < 15:
nalt = compare_alternatives(source)
if nalt > 1:
- print("--- {:3} lines, {:2} alternatives ---------".format(nlines, nalt))
+ print(f"--- {nlines:3} lines, {nalt:2} alternatives ---------")
print(source)
diff --git a/lab/parse_all.py b/lab/parse_all.py
index b14c1f0e..3b2465d9 100644
--- a/lab/parse_all.py
+++ b/lab/parse_all.py
@@ -3,17 +3,16 @@
import os
import sys
-from coverage.exceptions import CoverageException
from coverage.parser import PythonParser
for root, dirnames, filenames in os.walk(sys.argv[1]):
for filename in filenames:
if filename.endswith(".py"):
filename = os.path.join(root, filename)
- print(":: {}".format(filename))
+ print(f":: {filename}")
try:
par = PythonParser(filename=filename)
par.parse_source()
par.arcs()
except Exception as exc:
- print(" ** {}".format(exc))
+ print(f" ** {exc}")
diff --git a/lab/parser.py b/lab/parser.py
index bf203189..4e11662b 100644
--- a/lab/parser.py
+++ b/lab/parser.py
@@ -3,7 +3,6 @@
"""Parser.py: a main for invoking code in coverage/parser.py"""
-from __future__ import division
import collections
import glob
@@ -21,7 +20,7 @@ from coverage.python import get_python_source
opcode_counts = collections.Counter()
-class ParserMain(object):
+class ParserMain:
"""A main for code parsing experiments."""
def main(self, args):
@@ -65,9 +64,9 @@ class ParserMain(object):
if options.histogram:
total = sum(opcode_counts.values())
- print("{} total opcodes".format(total))
+ print(f"{total} total opcodes")
for opcode, number in opcode_counts.most_common():
- print("{:20s} {:6d} {:.1%}".format(opcode, number, number/total))
+ print(f"{opcode:20s} {number:6d} {number/total:.1%}")
def one_file(self, options, filename):
"""Process just one file."""
@@ -89,7 +88,7 @@ class ParserMain(object):
pyparser = PythonParser(text, filename=filename, exclude=r"no\s*cover")
pyparser.parse_source()
except Exception as err:
- print("%s" % (err,))
+ print(f"{err}")
return
if options.dis:
@@ -151,12 +150,12 @@ class ParserMain(object):
if srclines:
upto = upto or disline.lineno-1
while upto <= disline.lineno-1:
- print("%100s%s" % ("", srclines[upto]))
+ print("{:>100}{}".format("", srclines[upto]))
upto += 1
elif disline.offset > 0:
print("")
line = disgen.format_dis_line(disline)
- print("%-70s" % (line,))
+ print(f"{line:<70}")
print("")
@@ -211,7 +210,7 @@ def set_char(s, n, c):
def blanks(s):
"""Return the set of positions where s is blank."""
- return set(i for i, c in enumerate(s) if c == " ")
+ return {i for i, c in enumerate(s) if c == " "}
def first_all_blanks(ss):
diff --git a/lab/platform_info.py b/lab/platform_info.py
index 7ddde47a..1ea14bed 100644
--- a/lab/platform_info.py
+++ b/lab/platform_info.py
@@ -15,11 +15,11 @@ def whatever(f):
def dump_module(mod):
- print("\n### {} ---------------------------".format(mod.__name__))
+ print(f"\n### {mod.__name__} ---------------------------")
for name in dir(mod):
if name.startswith("_"):
continue
- print("{:30s}: {!r:.100}".format(name, whatever(getattr(mod, name))))
+ print(f"{name:30s}: {whatever(getattr(mod, name))!r:.100}")
for mod in [platform, sys]:
diff --git a/lab/show_platform.py b/lab/show_platform.py
index e4f4dc2a..a5c3d954 100644
--- a/lab/show_platform.py
+++ b/lab/show_platform.py
@@ -13,4 +13,4 @@ for n in dir(platform):
n += "()"
except:
continue
- print("%30s: %r" % (n, v))
+ print(f"{n:>30}: {v!r}")
diff --git a/lab/show_pyc.py b/lab/show_pyc.py
index 2e21eb64..393e84d2 100644
--- a/lab/show_pyc.py
+++ b/lab/show_pyc.py
@@ -28,18 +28,16 @@ def show_pyc_file(fname):
flags = struct.unpack('<L', f.read(4))[0]
hash_based = flags & 0x01
check_source = flags & 0x02
- print("flags 0x%08x" % (flags,))
+ print(f"flags 0x{flags:08x}")
if hash_based:
source_hash = f.read(8)
read_date_and_size = False
if read_date_and_size:
moddate = f.read(4)
modtime = time.asctime(time.localtime(struct.unpack('<L', moddate)[0]))
- print("moddate %s (%s)" % (binascii.hexlify(moddate), modtime))
- if sys.version_info >= (3, 3):
- # 3.3 added another long to the header (size).
- size = f.read(4)
- print("pysize %s (%d)" % (binascii.hexlify(size), struct.unpack('<L', size)[0]))
+ print(f"moddate {binascii.hexlify(moddate)} ({modtime})")
+ size = f.read(4)
+ print("pysize %s (%d)" % (binascii.hexlify(size), struct.unpack('<L', size)[0]))
code = marshal.load(f)
show_code(code)
@@ -92,13 +90,13 @@ def show_code(code, indent='', number=None):
label = ""
if number is not None:
label = "%d: " % number
- print("%s%scode" % (indent, label))
+ print(f"{indent}{label}code")
indent += " "
- print("%sname %r" % (indent, code.co_name))
+ print(f"{indent}name {code.co_name!r}")
print("%sargcount %d" % (indent, code.co_argcount))
print("%snlocals %d" % (indent, code.co_nlocals))
print("%sstacksize %d" % (indent, code.co_stacksize))
- print("%sflags %04x: %s" % (indent, code.co_flags, flag_words(code.co_flags, CO_FLAGS)))
+ print(f"{indent}flags {code.co_flags:04x}: {flag_words(code.co_flags, CO_FLAGS)}")
show_hex("code", code.co_code, indent=indent)
dis.disassemble(code)
print("%sconsts" % indent)
@@ -107,43 +105,36 @@ def show_code(code, indent='', number=None):
show_code(const, indent+" ", number=i)
else:
print(" %s%d: %r" % (indent, i, const))
- print("%snames %r" % (indent, code.co_names))
- print("%svarnames %r" % (indent, code.co_varnames))
- print("%sfreevars %r" % (indent, code.co_freevars))
- print("%scellvars %r" % (indent, code.co_cellvars))
- print("%sfilename %r" % (indent, code.co_filename))
+ print(f"{indent}names {code.co_names!r}")
+ print(f"{indent}varnames {code.co_varnames!r}")
+ print(f"{indent}freevars {code.co_freevars!r}")
+ print(f"{indent}cellvars {code.co_cellvars!r}")
+ print(f"{indent}filename {code.co_filename!r}")
print("%sfirstlineno %d" % (indent, code.co_firstlineno))
show_hex("lnotab", code.co_lnotab, indent=indent)
- print(" %s%s" % (indent, ", ".join("%r:%r" % (line, byte) for byte, line in lnotab_interpreted(code))))
+ print(" {}{}".format(indent, ", ".join(f"{line!r}:{byte!r}" for byte, line in lnotab_interpreted(code))))
if hasattr(code, "co_linetable"):
show_hex("linetable", code.co_linetable, indent=indent)
if hasattr(code, "co_lines"):
- print(" %sco_lines %s" % (
+ print(" {}co_lines {}".format(
indent,
- ", ".join("%r:%r-%r" % (line, start, end) for start, end, line in code.co_lines())
+ ", ".join(f"{line!r}:{start!r}-{end!r}" for start, end, line in code.co_lines())
))
def show_hex(label, h, indent):
h = binascii.hexlify(h)
if len(h) < 60:
- print("%s%s %s" % (indent, label, h.decode('ascii')))
+ print("{}{} {}".format(indent, label, h.decode('ascii')))
else:
- print("%s%s" % (indent, label))
+ print(f"{indent}{label}")
for i in range(0, len(h), 60):
- print("%s %s" % (indent, h[i:i+60].decode('ascii')))
+ print("{} {}".format(indent, h[i:i+60].decode('ascii')))
-if sys.version_info >= (3,):
- def bytes_to_ints(bytes_value):
- return bytes_value
-else:
- def bytes_to_ints(bytes_value):
- for byte in bytes_value:
- yield ord(byte)
def lnotab_interpreted(code):
# Adapted from dis.py in the standard library.
- byte_increments = bytes_to_ints(code.co_lnotab[0::2])
- line_increments = bytes_to_ints(code.co_lnotab[1::2])
+ byte_increments = code.co_lnotab[0::2]
+ line_increments = code.co_lnotab[1::2]
last_line_num = None
line_num = code.co_firstlineno
diff --git a/perf/bug397.py b/perf/bug397.py
index 390741e5..18c979b8 100644
--- a/perf/bug397.py
+++ b/perf/bug397.py
@@ -10,7 +10,6 @@ Run this file two ways under coverage and see that the times are the same:
Written by David MacIver as part of https://github.com/nedbat/coveragepy/issues/397
"""
-from __future__ import print_function
import sys
import random
@@ -52,4 +51,4 @@ if __name__ == '__main__':
for d in data:
hash_str(d)
timing.append(1000000 * (time.time() - start) / len(data))
- print("Runtime per example:", "%.2f +/- %.2f us" % (mean(timing), sd(timing)))
+ print("Runtime per example:", f"{mean(timing):.2f} +/- {sd(timing):.2f} us")
diff --git a/perf/perf_measure.py b/perf/perf_measure.py
index 652f0fa8..e8f9ea98 100644
--- a/perf/perf_measure.py
+++ b/perf/perf_measure.py
@@ -38,15 +38,15 @@ def child(line_count):
def mk_main(file_count, call_count, line_count):
lines = []
lines.extend(
- "import test{}".format(idx) for idx in range(file_count)
+ f"import test{idx}" for idx in range(file_count)
)
lines.extend(
- "test{}.parent({}, {})".format(idx, call_count, line_count) for idx in range(file_count)
+ f"test{idx}.parent({call_count}, {line_count})" for idx in range(file_count)
)
return "\n".join(lines)
-class StressTest(object):
+class StressTest:
def __init__(self):
self.module_cleaner = SuperModuleCleaner()
@@ -55,7 +55,7 @@ class StressTest(object):
self.module_cleaner.clean_local_file_imports()
for idx in range(file_count):
- make_file('test{}.py'.format(idx), TEST_FILE)
+ make_file(f'test{idx}.py', TEST_FILE)
make_file('testmain.py', mk_main(file_count, call_count, line_count))
# Run it once just to get the disk caches loaded up.
@@ -137,7 +137,7 @@ class StressTest(object):
yield kwargs['file_count'] * kwargs['call_count'] * kwargs['line_count']
ops = sum(sum(operations(thing)) for thing in ["file", "call", "line"])
- print("{:.1f}M operations".format(ops/1e6))
+ print(f"{ops/1e6:.1f}M operations")
def check_coefficients(self):
# For checking the calculation of actual stats:
@@ -161,14 +161,14 @@ class StressTest(object):
}
kwargs[thing+"_count"] = n
res = self._compute_overhead(**kwargs)
- per_thing.append(res.overhead / getattr(res, "{}s".format(thing)))
+ per_thing.append(res.overhead / getattr(res, f"{thing}s"))
pct_thing.append(res.covered / res.baseline * 100)
- out = "Per {}: ".format(thing)
+ out = f"Per {thing}: "
out += "mean = {:9.3f}us, stddev = {:8.3f}us, ".format(
statistics.mean(per_thing)*1e6, statistics.stdev(per_thing)*1e6
)
- out += "min = {:9.3f}us, ".format(min(per_thing)*1e6)
+ out += f"min = {min(per_thing)*1e6:9.3f}us, "
out += "pct = {:6.1f}%, stddev = {:6.1f}%".format(
statistics.mean(pct_thing), statistics.stdev(pct_thing)
)
@@ -181,7 +181,7 @@ class StressTest(object):
if __name__ == '__main__':
with tempfile.TemporaryDirectory(prefix="coverage_stress_") as tempdir:
- print("Working in {}".format(tempdir))
+ print(f"Working in {tempdir}")
os.chdir(tempdir)
sys.path.insert(0, ".")
diff --git a/perf/solve_poly.py b/perf/solve_poly.py
index 66231725..083dc544 100644
--- a/perf/solve_poly.py
+++ b/perf/solve_poly.py
@@ -10,7 +10,6 @@ import attr
import itertools
import numpy
import scipy.optimize
-import sys
def f(*args, simplify=False):
@@ -207,7 +206,7 @@ for row in INPUT.splitlines():
#print('\n'.join(str(t) for t in inputs_outputs.items()))
def calc_poly_coeff(poly, coefficients):
- c_tuples = list(((c,) for c in coefficients))
+ c_tuples = list((c,) for c in coefficients)
poly = list(f(*poly))
poly = list(a + b for a, b in zip(c_tuples, poly))
multiplied = list(m(*t) for t in poly)
@@ -241,7 +240,7 @@ with open('results', 'w') as f:
coefficients = [int(round(x)) for x in c.x]
terms = [''.join(t) for t in poly.terms]
- message = "{}' = ".format(name)
+ message = f"{name}' = "
message += ' + '.join("{}{}".format(coeff if coeff != 1 else '', term) for coeff, term in reversed(list(zip(coefficients, terms))) if coeff != 0)
print(message)
f.write(message)