Skip to content

Commit a24af26

Browse files
authored
Merge branch 'master' into bugfix/st-synthetic-named-expr-in-match
2 parents a772dc9 + 5e9d657 commit a24af26

File tree

7 files changed

+192
-4
lines changed

7 files changed

+192
-4
lines changed

misc/perf_compare.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,15 @@ def heading(s: str) -> None:
3535
print()
3636

3737

38-
def build_mypy(target_dir: str, multi_file: bool) -> 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"
4343
if multi_file:
4444
env["MYPYC_MULTI_FILE"] = "1"
45+
if cflags is not None:
46+
env["CFLAGS"] = cflags
4547
cmd = [sys.executable, "setup.py", "--use-mypyc", "build_ext", "--inplace"]
4648
subprocess.run(cmd, env=env, check=True, cwd=target_dir)
4749

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()

mypy/subtypes.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2117,7 +2117,8 @@ def covers_at_runtime(item: Type, supertype: Type) -> bool:
21172117
supertype = get_proper_type(supertype)
21182118

21192119
# Since runtime type checks will ignore type arguments, erase the types.
2120-
supertype = erase_type(supertype)
2120+
if not (isinstance(supertype, FunctionLike) and supertype.is_type_obj()):
2121+
supertype = erase_type(supertype)
21212122
if is_proper_subtype(
21222123
erase_type(item), supertype, ignore_promotions=True, erase_instances=True
21232124
):

mypy/typeanal.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1109,8 +1109,8 @@ def visit_callable_type(
11091109
variables = t.variables
11101110
else:
11111111
variables, _ = self.bind_function_type_variables(t, t)
1112-
type_guard = self.anal_type_guard(t.ret_type)
1113-
type_is = self.anal_type_is(t.ret_type)
1112+
type_guard = self.anal_type_guard(t.ret_type) if t.type_guard is None else t.type_guard
1113+
type_is = self.anal_type_is(t.ret_type) if t.type_is is None else t.type_is
11141114

11151115
arg_kinds = t.arg_kinds
11161116
arg_types = []

test-data/unit/check-python310.test

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2684,6 +2684,28 @@ def f(t: T) -> None:
26842684
reveal_type(k) # N: Revealed type is "tuple[builtins.int, fallback=__main__.K]"
26852685
[builtins fixtures/tuple.pyi]
26862686

2687+
[case testMatchTypeObjectTypeVar]
2688+
# flags: --warn-unreachable
2689+
from typing import TypeVar
2690+
import b
2691+
2692+
T_Choice = TypeVar("T_Choice", bound=b.One | b.Two)
2693+
2694+
def switch(choice: type[T_Choice]) -> None:
2695+
match choice:
2696+
case b.One:
2697+
reveal_type(choice) # N: Revealed type is "def () -> b.One"
2698+
case b.Two:
2699+
reveal_type(choice) # N: Revealed type is "def () -> b.Two"
2700+
case _:
2701+
reveal_type(choice) # N: Revealed type is "type[T_Choice`-1]"
2702+
2703+
[file b.py]
2704+
class One: ...
2705+
class Two: ...
2706+
2707+
[builtins fixtures/tuple.pyi]
2708+
26872709
[case testNewRedefineMatchBasics]
26882710
# flags: --allow-redefinition-new --local-partial-types
26892711

test-data/unit/check-typeguard.test

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -813,3 +813,20 @@ raw_target: object
813813
if isinstance(raw_target, type) and is_xlike(raw_target):
814814
reveal_type(raw_target) # N: Revealed type is "type[__main__.X]"
815815
[builtins fixtures/tuple.pyi]
816+
817+
[case testTypeGuardWithDefer]
818+
from typing import Union
819+
from typing_extensions import TypeGuard
820+
821+
class A: ...
822+
class B: ...
823+
824+
def is_a(x: object) -> TypeGuard[A]:
825+
return defer_not_defined() # E: Name "defer_not_defined" is not defined
826+
827+
def main(x: Union[A, B]) -> None:
828+
if is_a(x):
829+
reveal_type(x) # N: Revealed type is "__main__.A"
830+
else:
831+
reveal_type(x) # N: Revealed type is "Union[__main__.A, __main__.B]"
832+
[builtins fixtures/tuple.pyi]

test-data/unit/check-typeis.test

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -933,3 +933,20 @@ def main(f: Callable[[], int | Awaitable[int]]) -> None:
933933
else:
934934
reveal_type(f) # N: Revealed type is "def () -> Union[builtins.int, typing.Awaitable[builtins.int]]"
935935
[builtins fixtures/tuple.pyi]
936+
937+
[case testTypeIsWithDefer]
938+
from typing import Union
939+
from typing_extensions import TypeIs
940+
941+
class A: ...
942+
class B: ...
943+
944+
def is_a(x: object) -> TypeIs[A]:
945+
return defer_not_defined() # E: Name "defer_not_defined" is not defined
946+
947+
def main(x: Union[A, B]) -> None:
948+
if is_a(x):
949+
reveal_type(x) # N: Revealed type is "__main__.A"
950+
else:
951+
reveal_type(x) # N: Revealed type is "__main__.B"
952+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)