Skip to content

Commit f8689e9

Browse files
committed
Merge branch 'master' into mypyc-838-text-signatures
2 parents a4094d0 + 16e99de commit f8689e9

Some content is hidden

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

68 files changed

+1798
-298
lines changed

docs/source/generics.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -630,7 +630,7 @@ Let us illustrate this by few simple examples:
630630
631631
my_circles: list[Circle] = []
632632
add_one(my_circles) # This may appear safe, but...
633-
my_circles[-1].rotate() # ...this will fail, since my_circles[0] is now a Shape, not a Circle
633+
my_circles[0].rotate() # ...this will fail, since my_circles[0] is now a Shape, not a Circle
634634
635635
Another example of invariant type is ``dict``. Most mutable containers
636636
are invariant.

misc/perf_compare.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,15 @@ def heading(s: str) -> None:
3535
print()
3636

3737

38-
def build_mypy(target_dir: str) -> None:
38+
def build_mypy(target_dir: str, multi_file: bool, *, cflags: str | None = None) -> None:
3939
env = os.environ.copy()
4040
env["CC"] = "clang"
4141
env["MYPYC_OPT_LEVEL"] = "2"
4242
env["PYTHONHASHSEED"] = "1"
43+
if multi_file:
44+
env["MYPYC_MULTI_FILE"] = "1"
45+
if cflags is not None:
46+
env["CFLAGS"] = cflags
4347
cmd = [sys.executable, "setup.py", "--use-mypyc", "build_ext", "--inplace"]
4448
subprocess.run(cmd, env=env, check=True, cwd=target_dir)
4549

@@ -110,6 +114,12 @@ def main() -> None:
110114
action="store_true",
111115
help="measure incremental run (fully cached)",
112116
)
117+
parser.add_argument(
118+
"--multi-file",
119+
default=False,
120+
action="store_true",
121+
help="compile each mypy module to a separate C file (reduces RAM use)",
122+
)
113123
parser.add_argument(
114124
"--dont-setup",
115125
default=False,
@@ -127,9 +137,9 @@ def main() -> None:
127137
parser.add_argument(
128138
"-j",
129139
metavar="N",
130-
default=8,
140+
default=4,
131141
type=int,
132-
help="set maximum number of parallel builds (default=8)",
142+
help="set maximum number of parallel builds (default=4) -- high numbers require a lot of RAM!",
133143
)
134144
parser.add_argument(
135145
"-r",
@@ -155,6 +165,7 @@ def main() -> None:
155165
args = parser.parse_args()
156166
incremental: bool = args.incremental
157167
dont_setup: bool = args.dont_setup
168+
multi_file: bool = args.multi_file
158169
commits = args.commit
159170
num_runs: int = args.num_runs + 1
160171
max_workers: int = args.j
@@ -185,7 +196,9 @@ def main() -> None:
185196
print("(This will take a while...)")
186197

187198
with ThreadPoolExecutor(max_workers=max_workers) as executor:
188-
futures = [executor.submit(build_mypy, target_dir) for target_dir in target_dirs]
199+
futures = [
200+
executor.submit(build_mypy, target_dir, multi_file) for target_dir in target_dirs
201+
]
189202
for future in as_completed(futures):
190203
future.result()
191204

misc/profile_self_check.py

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
"""Compile mypy using mypyc and profile self-check using perf.
2+
3+
Notes:
4+
- Only Linux is supported for now (TODO: add support for other profilers)
5+
- The profile is collected at C level
6+
- It includes C functions compiled by mypyc and CPython runtime functions
7+
- The names of mypy functions are mangled to C names, but usually it's clear what they mean
8+
- Generally CPyDef_ prefix for native functions and CPyPy_ prefix for wrapper functions
9+
- It's important to compile CPython using special flags (see below) to get good results
10+
- Generally use the latest Python feature release (or the most recent beta if supported by mypyc)
11+
- The tool prints a command that can be used to analyze the profile afterwards
12+
13+
You may need to adjust kernel parameters temporarily, e.g. this (note that this has security
14+
implications):
15+
16+
sudo sysctl kernel.perf_event_paranoid=-1
17+
18+
This is the recommended way to configure CPython for profiling:
19+
20+
./configure \
21+
--enable-optimizations \
22+
--with-lto \
23+
CFLAGS="-O2 -g -fno-omit-frame-pointer"
24+
"""
25+
26+
import argparse
27+
import glob
28+
import os
29+
import shutil
30+
import subprocess
31+
import sys
32+
import time
33+
34+
from perf_compare import build_mypy, clone
35+
36+
# Use these C compiler flags when compiling mypy (important). Note that it's strongly recommended
37+
# to also compile CPython using similar flags, but we don't enforce it in this script.
38+
CFLAGS = "-O2 -fno-omit-frame-pointer -g"
39+
40+
# Generated files, including binaries, go under this directory to avoid overwriting user state.
41+
TARGET_DIR = "mypy.profile.tmpdir"
42+
43+
44+
def _profile_self_check(target_dir: str) -> None:
45+
cache_dir = os.path.join(target_dir, ".mypy_cache")
46+
if os.path.exists(cache_dir):
47+
shutil.rmtree(cache_dir)
48+
files = []
49+
for pat in "mypy/*.py", "mypy/*/*.py", "mypyc/*.py", "mypyc/test/*.py":
50+
files.extend(glob.glob(pat))
51+
self_check_cmd = ["python", "-m", "mypy", "--config-file", "mypy_self_check.ini"] + files
52+
cmdline = ["perf", "record", "-g"] + self_check_cmd
53+
t0 = time.time()
54+
subprocess.run(cmdline, cwd=target_dir, check=True)
55+
elapsed = time.time() - t0
56+
print(f"{elapsed:.2f}s elapsed")
57+
58+
59+
def profile_self_check(target_dir: str) -> None:
60+
try:
61+
_profile_self_check(target_dir)
62+
except subprocess.CalledProcessError:
63+
print("\nProfiling failed! You may missing some permissions.")
64+
print("\nThis may help (note that it has security implications):")
65+
print(" sudo sysctl kernel.perf_event_paranoid=-1")
66+
sys.exit(1)
67+
68+
69+
def check_requirements() -> None:
70+
if sys.platform != "linux":
71+
# TODO: How to make this work on other platforms?
72+
sys.exit("error: Only Linux is supported")
73+
74+
try:
75+
subprocess.run(["perf", "-h"], capture_output=True)
76+
except (subprocess.CalledProcessError, FileNotFoundError):
77+
print("error: The 'perf' profiler is not installed")
78+
sys.exit(1)
79+
80+
try:
81+
subprocess.run(["clang", "--version"], capture_output=True)
82+
except (subprocess.CalledProcessError, FileNotFoundError):
83+
print("error: The clang compiler is not installed")
84+
sys.exit(1)
85+
86+
if not os.path.isfile("mypy_self_check.ini"):
87+
print("error: Run this in the mypy repository root")
88+
sys.exit(1)
89+
90+
91+
def main() -> None:
92+
check_requirements()
93+
94+
parser = argparse.ArgumentParser(
95+
description="Compile mypy and profile self checking using 'perf'."
96+
)
97+
parser.add_argument(
98+
"--multi-file",
99+
action="store_true",
100+
help="compile mypy into one C file per module (to reduce RAM use during compilation)",
101+
)
102+
parser.add_argument(
103+
"--skip-compile", action="store_true", help="use compiled mypy from previous run"
104+
)
105+
args = parser.parse_args()
106+
multi_file: bool = args.multi_file
107+
skip_compile: bool = args.skip_compile
108+
109+
target_dir = TARGET_DIR
110+
111+
if not skip_compile:
112+
clone(target_dir, "HEAD")
113+
114+
print(f"Building mypy in {target_dir}...")
115+
build_mypy(target_dir, multi_file, cflags=CFLAGS)
116+
elif not os.path.isdir(target_dir):
117+
sys.exit("error: Can't find compile mypy from previous run -- can't use --skip-compile")
118+
119+
profile_self_check(target_dir)
120+
121+
print()
122+
print('NOTE: Compile CPython using CFLAGS="-O2 -g -fno-omit-frame-pointer" for good results')
123+
print()
124+
print("CPU profile collected. You can now analyze the profile:")
125+
print(f" perf report -i {target_dir}/perf.data ")
126+
127+
128+
if __name__ == "__main__":
129+
main()

misc/upload-pypi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def tmp_twine() -> Iterator[Path]:
108108
def upload_dist(dist: Path, dry_run: bool = True) -> None:
109109
with tmp_twine() as twine:
110110
files = [item for item in dist.iterdir() if item_ok_for_pypi(item.name)]
111-
cmd: list[Any] = [twine, "upload"]
111+
cmd: list[Any] = [twine, "upload", "--skip-existing"]
112112
cmd += files
113113
if dry_run:
114114
print("[dry run] " + " ".join(map(str, cmd)))

0 commit comments

Comments
 (0)