diff --git a/mypy/checker.py b/mypy/checker.py index fa7c645873d0..5a74f019dcf4 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -1076,6 +1076,8 @@ def check_func_item( if name == "__exit__": self.check__exit__return_type(defn) + # TODO: the following logic should move to the dataclasses plugin + # https://github.com/python/mypy/issues/15515 if name == "__post_init__": if dataclasses_plugin.is_processed_dataclass(defn.info): dataclasses_plugin.check_post_init(self, defn, defn.info) @@ -2882,7 +2884,8 @@ def check_assignment( typ = self.expr_checker.accept(rvalue) self.check_match_args(inferred, typ, lvalue) if name == "__post_init__": - if dataclasses_plugin.is_processed_dataclass(self.scope.active_class()): + active_class = self.scope.active_class() + if active_class and dataclasses_plugin.is_processed_dataclass(active_class): self.fail(message_registry.DATACLASS_POST_INIT_MUST_BE_A_FUNCTION, rvalue) # Defer PartialType's super type checking. diff --git a/mypy/nodes.py b/mypy/nodes.py index d29e99ccace7..6556cd910b46 100644 --- a/mypy/nodes.py +++ b/mypy/nodes.py @@ -515,7 +515,6 @@ def __init__(self) -> None: # Original, not semantically analyzed type (used for reprocessing) self.unanalyzed_type: mypy.types.ProperType | None = None # If method, reference to TypeInfo - # TODO: Type should be Optional[TypeInfo] self.info = FUNC_NO_INFO self.is_property = False self.is_class = False diff --git a/mypy/plugins/dataclasses.py b/mypy/plugins/dataclasses.py index 8b34c28b6832..99f079705c3f 100644 --- a/mypy/plugins/dataclasses.py +++ b/mypy/plugins/dataclasses.py @@ -1070,8 +1070,8 @@ def replace_function_sig_callback(ctx: FunctionSigContext) -> CallableType: ) -def is_processed_dataclass(info: TypeInfo | None) -> bool: - return info is not None and "dataclass" in info.metadata +def is_processed_dataclass(info: TypeInfo) -> bool: + return bool(info) and "dataclass" in info.metadata def check_post_init(api: TypeChecker, defn: FuncItem, info: TypeInfo) -> None: diff --git a/test-data/unit/check-dataclasses.test b/test-data/unit/check-dataclasses.test index 8a50e7124d05..35df84658259 100644 --- a/test-data/unit/check-dataclasses.test +++ b/test-data/unit/check-dataclasses.test @@ -2280,6 +2280,10 @@ reveal_type(a2) # N: Revealed type is "__main__.A[builtins.int]" [builtins fixtures/tuple.pyi] +[case testPostInitNotMethod] +def __post_init__() -> None: + pass + [case testPostInitCorrectSignature] from typing import Any, Generic, TypeVar, Callable, Self from dataclasses import dataclass, InitVar