Skip to content

Commit 7bf390b

Browse files
authored
Merge branch 'master' into bugfix/gh-19312-setter-of-nothing
2 parents ee52e56 + 1bf186c commit 7bf390b

Some content is hidden

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

57 files changed

+1676
-238
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/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: 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/checker.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2959,7 +2959,11 @@ def check_metaclass_compatibility(self, typ: TypeInfo) -> None:
29592959
"Metaclass conflict: the metaclass of a derived class must be "
29602960
"a (non-strict) subclass of the metaclasses of all its bases",
29612961
typ,
2962+
code=codes.METACLASS,
29622963
)
2964+
explanation = typ.explain_metaclass_conflict()
2965+
if explanation:
2966+
self.note(explanation, typ, code=codes.METACLASS)
29632967

29642968
def visit_import_from(self, node: ImportFrom) -> None:
29652969
for name, _ in node.names:

mypy/checkexpr.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2684,9 +2684,12 @@ def check_arg(
26842684
context=context,
26852685
outer_context=outer_context,
26862686
)
2687-
self.msg.incompatible_argument_note(
2688-
original_caller_type, callee_type, context, parent_error=error
2689-
)
2687+
if not caller_kind.is_star():
2688+
# For *args and **kwargs this note would be incorrect - we're comparing
2689+
# iterable/mapping type with union of relevant arg types.
2690+
self.msg.incompatible_argument_note(
2691+
original_caller_type, callee_type, context, parent_error=error
2692+
)
26902693
if not self.msg.prefer_simple_messages():
26912694
self.chk.check_possible_missing_await(
26922695
caller_type, callee_type, context, error.code

mypy/checkmember.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1477,23 +1477,18 @@ def bind_self_fast(method: F, original_type: Type | None = None) -> F:
14771477
items = [bind_self_fast(c, original_type) for c in method.items]
14781478
return cast(F, Overloaded(items))
14791479
assert isinstance(method, CallableType)
1480-
func: CallableType = method
1481-
if not func.arg_types:
1480+
if not method.arg_types:
14821481
# Invalid method, return something.
14831482
return method
1484-
if func.arg_kinds[0] in (ARG_STAR, ARG_STAR2):
1483+
if method.arg_kinds[0] in (ARG_STAR, ARG_STAR2):
14851484
# See typeops.py for details.
14861485
return method
1487-
original_type = get_proper_type(original_type)
1488-
if isinstance(original_type, CallableType) and original_type.is_type_obj():
1489-
original_type = TypeType.make_normalized(original_type.ret_type)
1490-
res = func.copy_modified(
1491-
arg_types=func.arg_types[1:],
1492-
arg_kinds=func.arg_kinds[1:],
1493-
arg_names=func.arg_names[1:],
1486+
return method.copy_modified(
1487+
arg_types=method.arg_types[1:],
1488+
arg_kinds=method.arg_kinds[1:],
1489+
arg_names=method.arg_names[1:],
14941490
is_bound=True,
14951491
)
1496-
return cast(F, res)
14971492

14981493

14991494
def has_operator(typ: Type, op_method: str, named_type: Callable[[str], Instance]) -> bool:

mypy/errorcodes.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,7 @@ def __hash__(self) -> int:
270270
"General",
271271
default_enabled=False,
272272
)
273+
METACLASS: Final[ErrorCode] = ErrorCode("metaclass", "Ensure that metaclass is valid", "General")
273274

274275
# Syntax errors are often blocking.
275276
SYNTAX: Final[ErrorCode] = ErrorCode("syntax", "Report syntax errors", "General")

mypy/nodes.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3402,6 +3402,43 @@ def calculate_metaclass_type(self) -> mypy.types.Instance | None:
34023402

34033403
return winner
34043404

3405+
def explain_metaclass_conflict(self) -> str | None:
3406+
# Compare to logic in calculate_metaclass_type
3407+
declared = self.declared_metaclass
3408+
if declared is not None and not declared.type.has_base("builtins.type"):
3409+
return None
3410+
if self._fullname == "builtins.type":
3411+
return None
3412+
3413+
winner = declared
3414+
if declared is None:
3415+
resolution_steps = []
3416+
else:
3417+
resolution_steps = [f'"{declared.type.fullname}" (metaclass of "{self.fullname}")']
3418+
for super_class in self.mro[1:]:
3419+
super_meta = super_class.declared_metaclass
3420+
if super_meta is None or super_meta.type is None:
3421+
continue
3422+
if winner is None:
3423+
winner = super_meta
3424+
resolution_steps.append(
3425+
f'"{winner.type.fullname}" (metaclass of "{super_class.fullname}")'
3426+
)
3427+
continue
3428+
if winner.type.has_base(super_meta.type.fullname):
3429+
continue
3430+
if super_meta.type.has_base(winner.type.fullname):
3431+
winner = super_meta
3432+
resolution_steps.append(
3433+
f'"{winner.type.fullname}" (metaclass of "{super_class.fullname}")'
3434+
)
3435+
continue
3436+
# metaclass conflict
3437+
conflict = f'"{super_meta.type.fullname}" (metaclass of "{super_class.fullname}")'
3438+
return f"{' > '.join(resolution_steps)} conflicts with {conflict}"
3439+
3440+
return None
3441+
34053442
def is_metaclass(self, *, precise: bool = False) -> bool:
34063443
return (
34073444
self.has_base("builtins.type")

mypy/semanal.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2719,7 +2719,7 @@ def infer_metaclass_and_bases_from_compat_helpers(self, defn: ClassDef) -> None:
27192719
if len(metas) == 0:
27202720
return
27212721
if len(metas) > 1:
2722-
self.fail("Multiple metaclass definitions", defn)
2722+
self.fail("Multiple metaclass definitions", defn, code=codes.METACLASS)
27232723
return
27242724
defn.metaclass = metas.pop()
27252725

@@ -2775,7 +2775,11 @@ def get_declared_metaclass(
27752775
elif isinstance(metaclass_expr, MemberExpr):
27762776
metaclass_name = get_member_expr_fullname(metaclass_expr)
27772777
if metaclass_name is None:
2778-
self.fail(f'Dynamic metaclass not supported for "{name}"', metaclass_expr)
2778+
self.fail(
2779+
f'Dynamic metaclass not supported for "{name}"',
2780+
metaclass_expr,
2781+
code=codes.METACLASS,
2782+
)
27792783
return None, False, True
27802784
sym = self.lookup_qualified(metaclass_name, metaclass_expr)
27812785
if sym is None:
@@ -2786,6 +2790,7 @@ def get_declared_metaclass(
27862790
self.fail(
27872791
f'Class cannot use "{sym.node.name}" as a metaclass (has type "Any")',
27882792
metaclass_expr,
2793+
code=codes.METACLASS,
27892794
)
27902795
return None, False, True
27912796
if isinstance(sym.node, PlaceholderNode):
@@ -2803,11 +2808,15 @@ def get_declared_metaclass(
28032808
metaclass_info = target.type
28042809

28052810
if not isinstance(metaclass_info, TypeInfo) or metaclass_info.tuple_type is not None:
2806-
self.fail(f'Invalid metaclass "{metaclass_name}"', metaclass_expr)
2811+
self.fail(
2812+
f'Invalid metaclass "{metaclass_name}"', metaclass_expr, code=codes.METACLASS
2813+
)
28072814
return None, False, False
28082815
if not metaclass_info.is_metaclass():
28092816
self.fail(
2810-
'Metaclasses not inheriting from "type" are not supported', metaclass_expr
2817+
'Metaclasses not inheriting from "type" are not supported',
2818+
metaclass_expr,
2819+
code=codes.METACLASS,
28112820
)
28122821
return None, False, False
28132822
inst = fill_typevars(metaclass_info)

0 commit comments

Comments
 (0)