Skip to content

Commit fbf7230

Browse files
committed
Do not allow TypedDict classes with metaclass=
1 parent a1648f5 commit fbf7230

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

mypy/semanal.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1745,6 +1745,8 @@ def analyze_typeddict_classdef(self, defn: ClassDef) -> bool:
17451745
if info is None:
17461746
self.mark_incomplete(defn.name, defn)
17471747
else:
1748+
if defn.keywords and "metaclass" in defn.keywords:
1749+
self.fail('"TypedDict" cannot have a metaclass', defn.keywords["metaclass"])
17481750
self.prepare_class_def(defn, info, custom_names=True)
17491751
return True
17501752
return False

test-data/unit/check-typeddict.test

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3396,3 +3396,39 @@ reveal_type(b["a"]) # N: Revealed type is "Union[builtins.str, None]"
33963396
reveal_type(b["g"]) # N: Revealed type is "Union[builtins.int, None]"
33973397
[builtins fixtures/dict.pyi]
33983398
[typing fixtures/typing-typeddict.pyi]
3399+
3400+
[case testTypedDictWithMetaclass]
3401+
from typing import TypedDict, Generic, TypeVar
3402+
3403+
T = TypeVar('T')
3404+
3405+
class Empty(TypedDict): ...
3406+
3407+
class WithKeys(TypedDict):
3408+
x: int
3409+
y: int
3410+
3411+
class GenericWithKeys(TypedDict, Generic[T]):
3412+
x: T
3413+
y: T
3414+
3415+
class Meta(type): ...
3416+
3417+
class WithMetaKeyword(TypedDict, metaclass=Meta): # E: "TypedDict" cannot have a metaclass
3418+
...
3419+
3420+
class GenericWithMetaKeyword(TypedDict, Generic[T], metaclass=Meta): # E: "TypedDict" cannot have a metaclass
3421+
...
3422+
3423+
class PositionOfErrorIsPrecise(
3424+
TypedDict,
3425+
metaclass=Meta, # E: "TypedDict" cannot have a metaclass
3426+
):
3427+
...
3428+
3429+
# We still don't allow this, because the implementation is much easier
3430+
# and it does not make any practical sense to do it:
3431+
class WithTypeMeta(TypedDict, metaclass=type): # E: "TypedDict" cannot have a metaclass
3432+
...
3433+
[builtins fixtures/dict.pyi]
3434+
[typing fixtures/typing-typeddict.pyi]

0 commit comments

Comments
 (0)