Skip to content

Commit d2e6918

Browse files
authored
Merge pull request #295 from faster-cpython/path-typing
More careful Path typing
2 parents bbb73df + d8980d0 commit d2e6918

File tree

17 files changed

+136
-88
lines changed

17 files changed

+136
-88
lines changed

bench_runner/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
@functools.cache
1515
def get_bench_runner_config(
16-
filepath: Path = Path("bench_runner.toml"),
16+
filepath: Path | str = Path("bench_runner.toml"),
1717
):
18-
with open(filepath, "rb") as fd:
18+
with Path(filepath).open("rb") as fd:
1919
return tomllib.load(fd)

bench_runner/git.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,12 @@
1010
import rich
1111

1212

13+
from .util import PathLike
14+
15+
1316
def get_log(
1417
format: str,
15-
dirname: Path,
18+
dirname: PathLike,
1619
ref: str | None = None,
1720
n: int = 1,
1821
extra: list[str] | None = None,
@@ -42,22 +45,22 @@ def get_log(
4245
).strip()
4346

4447

45-
def get_git_hash(dirname: Path) -> str:
48+
def get_git_hash(dirname: PathLike) -> str:
4649
return get_log("%h", dirname)
4750

4851

49-
def get_git_commit_date(dirname: Path) -> str:
52+
def get_git_commit_date(dirname: PathLike) -> str:
5053
return get_log("%cI", dirname)
5154

5255

53-
def remove(repodir: Path, path: Path) -> None:
56+
def remove(repodir: Path, path: PathLike) -> None:
5457
subprocess.check_output(
5558
["git", "rm", str(path)],
5659
cwd=repodir,
5760
)
5861

5962

60-
def get_git_merge_base(dirname: Path) -> str | None:
63+
def get_git_merge_base(dirname: PathLike) -> str | None:
6164
# We need to make sure we have commits from main that are old enough to be
6265
# the base of this branch, but not so old that we waste a ton of bandwidth
6366
commit_date = datetime.datetime.fromisoformat(get_git_commit_date(dirname))
@@ -109,14 +112,14 @@ def get_git_merge_base(dirname: Path) -> str | None:
109112
return merge_base
110113

111114

112-
def get_tags(dirname: Path) -> list[str]:
115+
def get_tags(dirname: PathLike) -> list[str]:
113116
subprocess.check_call(["git", "fetch", "--tags"], cwd=dirname)
114117
return subprocess.check_output(
115118
["git", "tag"], cwd=dirname, encoding="utf-8"
116119
).splitlines()
117120

118121

119-
def get_commits_between(dirname: Path, ref1: str, ref2: str) -> list[str]:
122+
def get_commits_between(dirname: PathLike, ref1: str, ref2: str) -> list[str]:
120123
return list(
121124
subprocess.check_output(
122125
["git", "rev-list", "--ancestry-path", f"{ref1}..{ref2}"],
@@ -126,6 +129,6 @@ def get_commits_between(dirname: Path, ref1: str, ref2: str) -> list[str]:
126129
)
127130

128131

129-
def bisect_commits(dirname: Path, ref1: str, ref2: str) -> str:
132+
def bisect_commits(dirname: PathLike, ref1: str, ref2: str) -> str:
130133
commits = get_commits_between(dirname, ref1, ref2)
131134
return commits[len(commits) // 2]

bench_runner/hpt.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,16 @@
3535
from numpy.typing import NDArray
3636

3737

38-
from bench_runner import util
39-
38+
from . import util
39+
from .util import PathLike
4040

4141
ACC_MAXSU = 2
4242

4343

4444
def load_from_json(
45-
json_path: Path,
45+
json_path: PathLike,
4646
) -> dict[str, NDArray[np.float64]]:
47-
with json_path.open() as fd:
47+
with Path(json_path).open() as fd:
4848
content = json.load(fd)
4949

5050
return load_data(content)
@@ -311,7 +311,7 @@ def maxspeedup(
311311
return base_su
312312

313313

314-
def make_report(ref: Path, head: Path, alpha=0.1):
314+
def make_report(ref: PathLike, head: PathLike, alpha=0.1):
315315
# The original code inverted the inputs from the standard in bench_runner,
316316
# and it's easier to just flip them here.
317317
a, b = head, ref

bench_runner/plot.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from . import config as mconfig
2525
from . import flags as mflags
2626
from . import result
27+
from .util import PathLike
2728

2829

2930
INTERPRETER_HEAVY = {
@@ -48,7 +49,7 @@
4849
}
4950

5051

51-
def savefig(output_filename: Path, **kwargs):
52+
def savefig(output_filename: PathLike, **kwargs):
5253
class Options:
5354
quiet = True
5455
remove_descriptive_elements = True
@@ -58,6 +59,8 @@ class Options:
5859
shorten_ids = True
5960
digits = 3
6061

62+
output_filename = Path(output_filename)
63+
6164
plt.savefig(output_filename, **kwargs)
6265
plt.close("all")
6366

@@ -139,7 +142,7 @@ def formatter(val, pos):
139142

140143
def plot_diff(
141144
combined_data: result.CombinedData,
142-
output_filename: Path,
145+
output_filename: PathLike,
143146
title: str,
144147
differences: tuple[str, str],
145148
) -> None:
@@ -227,7 +230,7 @@ def add_axvline(ax, dt: datetime.datetime, name: str):
227230

228231
def longitudinal_plot(
229232
results: Iterable[result.Result],
230-
output_filename: Path,
233+
output_filename: PathLike,
231234
getter: Callable[
232235
[result.BenchmarkComparison], float | None
233236
] = lambda r: r.hpt_percentile_float(99),
@@ -243,6 +246,7 @@ def get_comparison_value(ref, r, base):
243246
data[key] = value
244247
return value
245248

249+
output_filename = Path(output_filename)
246250
cfg = get_plot_config()
247251

248252
data_cache = output_filename.with_suffix(".json")
@@ -252,7 +256,7 @@ def get_comparison_value(ref, r, base):
252256
else:
253257
data = {}
254258

255-
axs: Sequence[matplotlib.Axes]
259+
axs: Sequence[matplotlib.Axes] # pyright: ignore
256260

257261
fig, axs = plt.subplots(
258262
len(cfg["versions"]),
@@ -350,7 +354,7 @@ def get_comparison_value(ref, r, base):
350354
json.dump(data, fd, indent=2)
351355

352356

353-
def _standardize_xlims(axs: Sequence[matplotlib.Axes]) -> None:
357+
def _standardize_xlims(axs: Sequence[matplotlib.Axes]) -> None: # pyright: ignore
354358
if not len(axs):
355359
return
356360

@@ -369,13 +373,15 @@ def _standardize_xlims(axs: Sequence[matplotlib.Axes]) -> None:
369373

370374
def flag_effect_plot(
371375
results: Iterable[result.Result],
372-
output_filename: Path,
376+
output_filename: PathLike,
373377
getter: Callable[
374378
[result.BenchmarkComparison], float | None
375379
] = lambda r: r.hpt_percentile_float(99),
376380
differences: tuple[str, str] = ("slower", "faster"),
377381
title="Performance improvement by configuration",
378382
):
383+
output_filename = Path(output_filename)
384+
379385
# We don't need to track the performance of the Tier 2 configuration
380386
all_flags = [flag for flag in mflags.FLAGS if flag.name != "PYTHON_UOPS"]
381387
flags = [flag.name for flag in reversed(all_flags)]
@@ -399,7 +405,7 @@ def get_comparison_value(ref, r):
399405
else:
400406
data = {}
401407

402-
axs: Sequence[matplotlib.Axes]
408+
axs: Sequence[matplotlib.Axes] # pyright: ignore
403409

404410
fig, axs = plt.subplots(
405411
len(flags), 1, figsize=(10, 5 * len(flags)), layout="constrained"

bench_runner/result.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from . import plot
3131
from . import runners
3232
from . import util
33+
from .util import PathLike
3334

3435

3536
CombinedData = list[tuple[str, np.ndarray | None, float]]
@@ -54,7 +55,7 @@ def _clean_for_url(string: str) -> str:
5455
return string.replace("-", "%2d")
5556

5657

57-
def _get_platform_value(python: Path, item: str) -> str:
58+
def _get_platform_value(python: PathLike, item: str) -> str:
5859
"""
5960
Get a value from the platform module of the given Python interpreter.
6061
"""
@@ -64,7 +65,7 @@ def _get_platform_value(python: Path, item: str) -> str:
6465
return output.strip().lower()
6566

6667

67-
def _get_architecture(python: Path) -> str:
68+
def _get_architecture(python: PathLike) -> str:
6869
machine = _get_platform_value(python, "machine")
6970
bits = eval(_get_platform_value(python, "architecture"))[0]
7071
if bits == "32bit":
@@ -152,7 +153,9 @@ def _generate_contents(self) -> str:
152153
fd.write(f"- memory change: {self._calculate_memory_change()}")
153154
return fd.getvalue()
154155

155-
def write_table(self, filename: Path) -> str | None:
156+
def write_table(self, filename: PathLike) -> str | None:
157+
filename = Path(filename)
158+
156159
entries = [
157160
("fork", unquote(self.head.fork)),
158161
("ref", self.head.ref),
@@ -212,7 +215,7 @@ def get_timing_diff(self) -> CombinedData:
212215
head_data = self.head.get_timing_data()
213216
return self._get_combined_data(ref_data, head_data)
214217

215-
def write_timing_plot(self, filename: Path) -> None:
218+
def write_timing_plot(self, filename: PathLike) -> None:
216219
plot.plot_diff(
217220
self.get_timing_diff(),
218221
filename,
@@ -231,7 +234,7 @@ def get_memory_diff(self) -> CombinedData:
231234
# Explicitly reversed so higher is bigger
232235
return self._get_combined_data(head_data, ref_data)
233236

234-
def write_memory_plot(self, filename: Path) -> None:
237+
def write_memory_plot(self, filename: PathLike) -> None:
235238
plot.plot_diff(
236239
self.get_memory_diff(),
237240
filename,
@@ -376,7 +379,9 @@ def get_files(self) -> Iterable[tuple[Callable, str, str]]:
376379
return
377380
yield (self.write_pystats_diff, ".md", "pystats diff")
378381

379-
def write_pystats_diff(self, filename: Path) -> None:
382+
def write_pystats_diff(self, filename: PathLike) -> None:
383+
filename = Path(filename)
384+
380385
try:
381386
contents = subprocess.check_output(
382387
[
@@ -434,7 +439,8 @@ def __init__(
434439
self.bases = {}
435440

436441
@classmethod
437-
def from_filename(cls, filename: Path) -> "Result":
442+
def from_filename(cls, filename: PathLike) -> "Result":
443+
filename = Path(filename)
438444
(
439445
name,
440446
_,
@@ -469,7 +475,7 @@ def from_filename(cls, filename: Path) -> "Result":
469475
@classmethod
470476
def from_scratch(
471477
cls,
472-
python: Path,
478+
python: PathLike,
473479
fork: str,
474480
ref: str,
475481
extra: Iterable[str] | None = None,
@@ -687,7 +693,7 @@ def memory_value(metadata):
687693

688694

689695
def has_result(
690-
results_dir: Path,
696+
results_dir: PathLike,
691697
commit_hash: str,
692698
machine: str,
693699
pystats: bool,
@@ -822,14 +828,14 @@ def track(it, *_args, **_kwargs):
822828

823829
def load_all_results(
824830
bases: Sequence[str] | None,
825-
results_dir: Path,
831+
results_dir: PathLike,
826832
sorted: bool = True,
827833
match: bool = True,
828834
progress: bool = True,
829835
) -> list[Result]:
830836
results = []
831837

832-
for entry in results_dir.glob("**/*.json"):
838+
for entry in Path(results_dir).glob("**/*.json"):
833839
result = Result.from_filename(entry)
834840
if result.result_info[0] not in ["raw results", "pystats raw"]:
835841
continue

0 commit comments

Comments
 (0)