Skip to content

Commit

Permalink
Do not allow TypedDict classes with metaclass=
Browse files Browse the repository at this point in the history
  • Loading branch information
sobolevn committed Nov 9, 2023
1 parent a1648f5 commit fbf7230
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
2 changes: 2 additions & 0 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1745,6 +1745,8 @@ def analyze_typeddict_classdef(self, defn: ClassDef) -> bool:
if info is None:
self.mark_incomplete(defn.name, defn)
else:
if defn.keywords and "metaclass" in defn.keywords:
self.fail('"TypedDict" cannot have a metaclass', defn.keywords["metaclass"])
self.prepare_class_def(defn, info, custom_names=True)
return True
return False
Expand Down
36 changes: 36 additions & 0 deletions test-data/unit/check-typeddict.test
Original file line number Diff line number Diff line change
Expand Up @@ -3396,3 +3396,39 @@ reveal_type(b["a"]) # N: Revealed type is "Union[builtins.str, None]"
reveal_type(b["g"]) # N: Revealed type is "Union[builtins.int, None]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictWithMetaclass]
from typing import TypedDict, Generic, TypeVar

T = TypeVar('T')

class Empty(TypedDict): ...

class WithKeys(TypedDict):
x: int
y: int

class GenericWithKeys(TypedDict, Generic[T]):
x: T
y: T

class Meta(type): ...

class WithMetaKeyword(TypedDict, metaclass=Meta): # E: "TypedDict" cannot have a metaclass
...

class GenericWithMetaKeyword(TypedDict, Generic[T], metaclass=Meta): # E: "TypedDict" cannot have a metaclass
...

class PositionOfErrorIsPrecise(
TypedDict,
metaclass=Meta, # E: "TypedDict" cannot have a metaclass
):
...

# We still don't allow this, because the implementation is much easier
# and it does not make any practical sense to do it:
class WithTypeMeta(TypedDict, metaclass=type): # E: "TypedDict" cannot have a metaclass
...
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

0 comments on commit fbf7230

Please sign in to comment.