Skip to content

Commit 6661705

Browse files
authored
Merge branch 'master' into fix/fix_narrow_promotions_in_unions
2 parents 17d4218 + 0b7afda commit 6661705

File tree

115 files changed

+3596
-678
lines changed

Some content is hidden

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

115 files changed

+3596
-678
lines changed

docs/source/error_code_list.rst

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,35 @@ You can use :py:class:`~collections.abc.Callable` as the type for callable objec
215215
for x in objs:
216216
f(x)
217217
218+
.. _code-metaclass:
219+
220+
Check the validity of a class's metaclass [metaclass]
221+
-----------------------------------------------------
222+
223+
Mypy checks whether the metaclass of a class is valid. The metaclass
224+
must be a subclass of ``type``. Further, the class hierarchy must yield
225+
a consistent metaclass. For more details, see the
226+
`Python documentation <https://docs.python.org/3.13/reference/datamodel.html#determining-the-appropriate-metaclass>`_
227+
228+
Note that mypy's metaclass checking is limited and may produce false-positives.
229+
See also :ref:`limitations`.
230+
231+
Example with an error:
232+
233+
.. code-block:: python
234+
235+
class GoodMeta(type):
236+
pass
237+
238+
class BadMeta:
239+
pass
240+
241+
class A1(metaclass=GoodMeta): # OK
242+
pass
243+
244+
class A2(metaclass=BadMeta): # Error: Metaclasses not inheriting from "type" are not supported [metaclass]
245+
pass
246+
218247
.. _code-var-annotated:
219248

220249
Require annotation if variable type is unclear [var-annotated]

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.

docs/source/metaclasses.rst

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,28 @@ so it's better not to combine metaclasses and class hierarchies:
9090
* ``Self`` is not allowed as annotation in metaclasses as per `PEP 673`_.
9191

9292
.. _PEP 673: https://peps.python.org/pep-0673/#valid-locations-for-self
93+
94+
For some builtin types, mypy may think their metaclass is :py:class:`abc.ABCMeta`
95+
even if it is :py:class:`type` at runtime. In those cases, you can either:
96+
97+
* use :py:class:`abc.ABCMeta` instead of :py:class:`type` as the
98+
superclass of your metaclass if that works in your use-case
99+
* mute the error with ``# type: ignore[metaclass]``
100+
101+
.. code-block:: python
102+
103+
import abc
104+
105+
assert type(tuple) is type # metaclass of tuple is type at runtime
106+
107+
# The problem:
108+
class M0(type): pass
109+
class A0(tuple, metaclass=M0): pass # Mypy Error: metaclass conflict
110+
111+
# Option 1: use ABCMeta instead of type
112+
class M1(abc.ABCMeta): pass
113+
class A1(tuple, metaclass=M1): pass
114+
115+
# Option 2: mute the error
116+
class M2(type): pass
117+
class A2(tuple, metaclass=M2): pass # type: ignore[metaclass]

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_check.py

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