Skip to content

Commit 401a63b

Browse files
committed
style: modernize type hints, a few more f-strings
I used: ``` ruff --select=UP,F --unsafe-fixes --fix *.py {coverage,tests,ci}/*.py ``` and then fixed a few "unused imports" that are actually needed by hand.
1 parent e4e238a commit 401a63b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

62 files changed

+719
-735
lines changed

coverage/__init__.py

-1
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,3 @@
3939
# On Windows, we encode and decode deep enough that something goes wrong and
4040
# the encodings.utf_8 module is loaded and then unloaded, I don't know why.
4141
# Adding a reference here prevents it from being unloaded. Yuk.
42-
import encodings.utf_8 # pylint: disable=wrong-import-position, wrong-import-order

coverage/annotate.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import os
99
import re
1010

11-
from typing import Iterable, Optional, TYPE_CHECKING
11+
from typing import Iterable, TYPE_CHECKING
1212

1313
from coverage.files import flat_rootname
1414
from coverage.misc import ensure_dir, isolate_module
@@ -48,12 +48,12 @@ class AnnotateReporter:
4848
def __init__(self, coverage: Coverage) -> None:
4949
self.coverage = coverage
5050
self.config = self.coverage.config
51-
self.directory: Optional[str] = None
51+
self.directory: str | None = None
5252

5353
blank_re = re.compile(r"\s*(#|$)")
5454
else_re = re.compile(r"\s*else\s*:\s*(#|$)")
5555

56-
def report(self, morfs: Optional[Iterable[TMorf]], directory: Optional[str] = None) -> None:
56+
def report(self, morfs: Iterable[TMorf] | None, directory: str | None = None) -> None:
5757
"""Run the report.
5858
5959
See `coverage.report()` for arguments.

coverage/cmdline.py

+17-17
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import textwrap
1515
import traceback
1616

17-
from typing import cast, Any, List, NoReturn, Optional, Tuple
17+
from typing import cast, Any, NoReturn
1818

1919
import coverage
2020
from coverage import Coverage
@@ -281,7 +281,7 @@ class OptionParserError(Exception):
281281
"""Used to stop the optparse error handler ending the process."""
282282
pass
283283

284-
def parse_args_ok(self, args: List[str]) -> Tuple[bool, Optional[optparse.Values], List[str]]:
284+
def parse_args_ok(self, args: list[str]) -> tuple[bool, optparse.Values | None, list[str]]:
285285
"""Call optparse.parse_args, but return a triple:
286286
287287
(ok, options, args)
@@ -317,9 +317,9 @@ class CmdOptionParser(CoverageOptionParser):
317317
def __init__(
318318
self,
319319
action: str,
320-
options: List[optparse.Option],
320+
options: list[optparse.Option],
321321
description: str,
322-
usage: Optional[str] = None,
322+
usage: str | None = None,
323323
):
324324
"""Create an OptionParser for a coverage.py command.
325325
@@ -549,9 +549,9 @@ def get_prog_name(self) -> str:
549549

550550

551551
def show_help(
552-
error: Optional[str] = None,
553-
topic: Optional[str] = None,
554-
parser: Optional[optparse.OptionParser] = None,
552+
error: str | None = None,
553+
topic: str | None = None,
554+
parser: optparse.OptionParser | None = None,
555555
) -> None:
556556
"""Display an error message, or the named topic."""
557557
assert error or topic or parser
@@ -605,7 +605,7 @@ def __init__(self) -> None:
605605
self.global_option = False
606606
self.coverage: Coverage
607607

608-
def command_line(self, argv: List[str]) -> int:
608+
def command_line(self, argv: list[str]) -> int:
609609
"""The bulk of the command line interface to coverage.py.
610610
611611
`argv` is the argument list to process.
@@ -620,7 +620,7 @@ def command_line(self, argv: List[str]) -> int:
620620

621621
# The command syntax we parse depends on the first argument. Global
622622
# switch syntax always starts with an option.
623-
parser: Optional[optparse.OptionParser]
623+
parser: optparse.OptionParser | None
624624
self.global_option = argv[0].startswith("-")
625625
if self.global_option:
626626
parser = GlobalOptionParser()
@@ -772,7 +772,7 @@ def command_line(self, argv: List[str]) -> int:
772772
def do_help(
773773
self,
774774
options: optparse.Values,
775-
args: List[str],
775+
args: list[str],
776776
parser: optparse.OptionParser,
777777
) -> bool:
778778
"""Deal with help requests.
@@ -807,7 +807,7 @@ def do_help(
807807

808808
return False
809809

810-
def do_run(self, options: optparse.Values, args: List[str]) -> int:
810+
def do_run(self, options: optparse.Values, args: list[str]) -> int:
811811
"""Implementation of 'coverage run'."""
812812

813813
if not args:
@@ -866,7 +866,7 @@ def do_run(self, options: optparse.Values, args: List[str]) -> int:
866866

867867
return OK
868868

869-
def do_debug(self, args: List[str]) -> int:
869+
def do_debug(self, args: list[str]) -> int:
870870
"""Implementation of 'coverage debug'."""
871871

872872
if not args:
@@ -899,7 +899,7 @@ def do_debug(self, args: List[str]) -> int:
899899
return OK
900900

901901

902-
def unshell_list(s: str) -> Optional[List[str]]:
902+
def unshell_list(s: str) -> list[str] | None:
903903
"""Turn a command-line argument into a list."""
904904
if not s:
905905
return None
@@ -913,7 +913,7 @@ def unshell_list(s: str) -> Optional[List[str]]:
913913
return s.split(",")
914914

915915

916-
def unglob_args(args: List[str]) -> List[str]:
916+
def unglob_args(args: list[str]) -> list[str]:
917917
"""Interpret shell wildcards for platforms that need it."""
918918
if env.WINDOWS:
919919
globbed = []
@@ -958,7 +958,7 @@ def unglob_args(args: List[str]) -> List[str]:
958958
}
959959

960960

961-
def main(argv: Optional[List[str]] = None) -> Optional[int]:
961+
def main(argv: list[str] | None = None) -> int | None:
962962
"""The main entry point to coverage.py.
963963
964964
This is installed as the script entry point.
@@ -997,8 +997,8 @@ def main(argv: Optional[List[str]] = None) -> Optional[int]:
997997
original_main = main
998998

999999
def main( # pylint: disable=function-redefined
1000-
argv: Optional[List[str]] = None,
1001-
) -> Optional[int]:
1000+
argv: list[str] | None = None,
1001+
) -> int | None:
10021002
"""A wrapper around main that profiles."""
10031003
profiler = SimpleLauncher.launch()
10041004
try:

coverage/collector.py

+18-18
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from types import FrameType
1313
from typing import (
14-
cast, Any, Callable, Dict, List, Mapping, Optional, Set, Type, TypeVar,
14+
cast, Any, Callable, Dict, List, Mapping, Set, TypeVar,
1515
)
1616

1717
from coverage import env
@@ -70,7 +70,7 @@ class Collector:
7070
# The stack of active Collectors. Collectors are added here when started,
7171
# and popped when stopped. Collectors on the stack are paused when not
7272
# the top, and resumed when they become the top again.
73-
_collectors: List[Collector] = []
73+
_collectors: list[Collector] = []
7474

7575
# The concurrency settings we support here.
7676
LIGHT_THREADS = {"greenlet", "eventlet", "gevent"}
@@ -79,12 +79,12 @@ def __init__(
7979
self,
8080
should_trace: Callable[[str, FrameType], TFileDisposition],
8181
check_include: Callable[[str, FrameType], bool],
82-
should_start_context: Optional[Callable[[FrameType], Optional[str]]],
82+
should_start_context: Callable[[FrameType], str | None] | None,
8383
file_mapper: Callable[[str], str],
8484
timid: bool,
8585
branch: bool,
8686
warn: TWarnFn,
87-
concurrency: List[str],
87+
concurrency: list[str],
8888
metacov: bool,
8989
) -> None:
9090
"""Create a collector.
@@ -136,16 +136,16 @@ def __init__(
136136

137137
self.covdata: CoverageData
138138
self.threading = None
139-
self.static_context: Optional[str] = None
139+
self.static_context: str | None = None
140140

141141
self.origin = short_stack()
142142

143143
self.concur_id_func = None
144144

145-
self._trace_class: Type[TracerCore]
146-
self.file_disposition_class: Type[TFileDisposition]
145+
self._trace_class: type[TracerCore]
146+
self.file_disposition_class: type[TFileDisposition]
147147

148-
core: Optional[str]
148+
core: str | None
149149
if timid:
150150
core = "pytrace"
151151
else:
@@ -240,7 +240,7 @@ def __init__(
240240
def __repr__(self) -> str:
241241
return f"<Collector at {id(self):#x}: {self.tracer_name()}>"
242242

243-
def use_data(self, covdata: CoverageData, context: Optional[str]) -> None:
243+
def use_data(self, covdata: CoverageData, context: str | None) -> None:
244244
"""Use `covdata` for recording data."""
245245
self.covdata = covdata
246246
self.static_context = context
@@ -268,9 +268,9 @@ def reset(self) -> None:
268268

269269
# A dictionary mapping file names to file tracer plugin names that will
270270
# handle them.
271-
self.file_tracers: Dict[str, str] = {}
271+
self.file_tracers: dict[str, str] = {}
272272

273-
self.disabled_plugins: Set[str] = set()
273+
self.disabled_plugins: set[str] = set()
274274

275275
# The .should_trace_cache attribute is a cache from file names to
276276
# coverage.FileDisposition objects, or None. When a file is first
@@ -301,7 +301,7 @@ def reset(self) -> None:
301301
self.should_trace_cache = {}
302302

303303
# Our active Tracers.
304-
self.tracers: List[TracerCore] = []
304+
self.tracers: list[TracerCore] = []
305305

306306
self._clear_data()
307307

@@ -342,12 +342,12 @@ def _start_tracer(self) -> TTraceFn | None:
342342
#
343343
# New in 3.12: threading.settrace_all_threads: https://github.com/python/cpython/pull/96681
344344

345-
def _installation_trace(self, frame: FrameType, event: str, arg: Any) -> Optional[TTraceFn]:
345+
def _installation_trace(self, frame: FrameType, event: str, arg: Any) -> TTraceFn | None:
346346
"""Called on new threads, installs the real tracer."""
347347
# Remove ourselves as the trace function.
348348
sys.settrace(None)
349349
# Install the real tracer.
350-
fn: Optional[TTraceFn] = self._start_tracer()
350+
fn: TTraceFn | None = self._start_tracer()
351351
# Invoke the real trace function with the current event, to be sure
352352
# not to lose an event.
353353
if fn:
@@ -444,9 +444,9 @@ def _activity(self) -> bool:
444444
"""
445445
return any(tracer.activity() for tracer in self.tracers)
446446

447-
def switch_context(self, new_context: Optional[str]) -> None:
447+
def switch_context(self, new_context: str | None) -> None:
448448
"""Switch to a new dynamic context."""
449-
context: Optional[str]
449+
context: str | None
450450
self.flush_data()
451451
if self.static_context:
452452
context = self.static_context
@@ -471,7 +471,7 @@ def cached_mapped_file(self, filename: str) -> str:
471471
"""A locally cached version of file names mapped through file_mapper."""
472472
return self.file_mapper(filename)
473473

474-
def mapped_file_dict(self, d: Mapping[str, T]) -> Dict[str, T]:
474+
def mapped_file_dict(self, d: Mapping[str, T]) -> dict[str, T]:
475475
"""Return a dict like d, but with keys modified by file_mapper."""
476476
# The call to list(items()) ensures that the GIL protects the dictionary
477477
# iterator against concurrent modifications by tracers running
@@ -511,7 +511,7 @@ def flush_data(self) -> bool:
511511
# Unpack the line number pairs packed into integers. See
512512
# tracer.c:CTracer_record_pair for the C code that creates
513513
# these packed ints.
514-
arc_data: Dict[str, List[TArc]] = {}
514+
arc_data: dict[str, list[TArc]] = {}
515515
packed_data = cast(Dict[str, Set[int]], self.data)
516516

517517
# The list() here and in the inner loop are to get a clean copy

0 commit comments

Comments
 (0)