Skip to content

Commit b83b870

Browse files
authored
Merge branch 'master' into try-finally-await
2 parents 12b533b + cbe28b2 commit b83b870

Some content is hidden

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

42 files changed

+1118
-215
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]

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
@@ -2702,7 +2702,7 @@ def infer_metaclass_and_bases_from_compat_helpers(self, defn: ClassDef) -> None:
27022702
if len(metas) == 0:
27032703
return
27042704
if len(metas) > 1:
2705-
self.fail("Multiple metaclass definitions", defn)
2705+
self.fail("Multiple metaclass definitions", defn, code=codes.METACLASS)
27062706
return
27072707
defn.metaclass = metas.pop()
27082708

@@ -2758,7 +2758,11 @@ def get_declared_metaclass(
27582758
elif isinstance(metaclass_expr, MemberExpr):
27592759
metaclass_name = get_member_expr_fullname(metaclass_expr)
27602760
if metaclass_name is None:
2761-
self.fail(f'Dynamic metaclass not supported for "{name}"', metaclass_expr)
2761+
self.fail(
2762+
f'Dynamic metaclass not supported for "{name}"',
2763+
metaclass_expr,
2764+
code=codes.METACLASS,
2765+
)
27622766
return None, False, True
27632767
sym = self.lookup_qualified(metaclass_name, metaclass_expr)
27642768
if sym is None:
@@ -2769,6 +2773,7 @@ def get_declared_metaclass(
27692773
self.fail(
27702774
f'Class cannot use "{sym.node.name}" as a metaclass (has type "Any")',
27712775
metaclass_expr,
2776+
code=codes.METACLASS,
27722777
)
27732778
return None, False, True
27742779
if isinstance(sym.node, PlaceholderNode):
@@ -2786,11 +2791,15 @@ def get_declared_metaclass(
27862791
metaclass_info = target.type
27872792

27882793
if not isinstance(metaclass_info, TypeInfo) or metaclass_info.tuple_type is not None:
2789-
self.fail(f'Invalid metaclass "{metaclass_name}"', metaclass_expr)
2794+
self.fail(
2795+
f'Invalid metaclass "{metaclass_name}"', metaclass_expr, code=codes.METACLASS
2796+
)
27902797
return None, False, False
27912798
if not metaclass_info.is_metaclass():
27922799
self.fail(
2793-
'Metaclasses not inheriting from "type" are not supported', metaclass_expr
2800+
'Metaclasses not inheriting from "type" are not supported',
2801+
metaclass_expr,
2802+
code=codes.METACLASS,
27942803
)
27952804
return None, False, False
27962805
inst = fill_typevars(metaclass_info)

mypy/typeops.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -472,9 +472,6 @@ class B(A): pass
472472
else:
473473
variables = func.variables
474474

475-
original_type = get_proper_type(original_type)
476-
if isinstance(original_type, CallableType) and original_type.is_type_obj():
477-
original_type = TypeType.make_normalized(original_type.ret_type)
478475
res = func.copy_modified(
479476
arg_types=func.arg_types[1:],
480477
arg_kinds=func.arg_kinds[1:],

mypy/typeshed/stdlib/VERSIONS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ asyncio.staggered: 3.8-
9595
asyncio.taskgroups: 3.11-
9696
asyncio.threads: 3.9-
9797
asyncio.timeouts: 3.11-
98+
asyncio.tools: 3.14-
9899
asyncio.trsock: 3.8-
99100
asyncore: 3.0-3.11
100101
atexit: 3.0-

mypy/typeshed/stdlib/_csv.pyi

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ else:
9090

9191
def writer(
9292
csvfile: SupportsWrite[str],
93+
/,
9394
dialect: _DialectLike = "excel",
9495
*,
9596
delimiter: str = ",",
@@ -103,6 +104,7 @@ def writer(
103104
) -> _writer: ...
104105
def reader(
105106
csvfile: Iterable[str],
107+
/,
106108
dialect: _DialectLike = "excel",
107109
*,
108110
delimiter: str = ",",

mypy/typeshed/stdlib/_zstd.pyi

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ class ZstdCompressor:
5252
self, /, data: ReadableBuffer, mode: _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 0
5353
) -> bytes: ...
5454
def flush(self, /, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 2) -> bytes: ...
55+
def set_pledged_input_size(self, size: int | None, /) -> None: ...
5556
@property
5657
def last_mode(self) -> _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame: ...
5758

0 commit comments

Comments
 (0)