Skip to content

Commit f9dc561

Browse files
authored
Fix __post_init__() internal error (#16080)
Fixes #16057.
1 parent 4941983 commit f9dc561

File tree

4 files changed

+10
-4
lines changed

4 files changed

+10
-4
lines changed

mypy/checker.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1076,6 +1076,8 @@ def check_func_item(
10761076

10771077
if name == "__exit__":
10781078
self.check__exit__return_type(defn)
1079+
# TODO: the following logic should move to the dataclasses plugin
1080+
# https://github.com/python/mypy/issues/15515
10791081
if name == "__post_init__":
10801082
if dataclasses_plugin.is_processed_dataclass(defn.info):
10811083
dataclasses_plugin.check_post_init(self, defn, defn.info)
@@ -2882,7 +2884,8 @@ def check_assignment(
28822884
typ = self.expr_checker.accept(rvalue)
28832885
self.check_match_args(inferred, typ, lvalue)
28842886
if name == "__post_init__":
2885-
if dataclasses_plugin.is_processed_dataclass(self.scope.active_class()):
2887+
active_class = self.scope.active_class()
2888+
if active_class and dataclasses_plugin.is_processed_dataclass(active_class):
28862889
self.fail(message_registry.DATACLASS_POST_INIT_MUST_BE_A_FUNCTION, rvalue)
28872890

28882891
# Defer PartialType's super type checking.

mypy/nodes.py

-1
Original file line numberDiff line numberDiff line change
@@ -515,7 +515,6 @@ def __init__(self) -> None:
515515
# Original, not semantically analyzed type (used for reprocessing)
516516
self.unanalyzed_type: mypy.types.ProperType | None = None
517517
# If method, reference to TypeInfo
518-
# TODO: Type should be Optional[TypeInfo]
519518
self.info = FUNC_NO_INFO
520519
self.is_property = False
521520
self.is_class = False

mypy/plugins/dataclasses.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1070,8 +1070,8 @@ def replace_function_sig_callback(ctx: FunctionSigContext) -> CallableType:
10701070
)
10711071

10721072

1073-
def is_processed_dataclass(info: TypeInfo | None) -> bool:
1074-
return info is not None and "dataclass" in info.metadata
1073+
def is_processed_dataclass(info: TypeInfo) -> bool:
1074+
return bool(info) and "dataclass" in info.metadata
10751075

10761076

10771077
def check_post_init(api: TypeChecker, defn: FuncItem, info: TypeInfo) -> None:

test-data/unit/check-dataclasses.test

+4
Original file line numberDiff line numberDiff line change
@@ -2280,6 +2280,10 @@ reveal_type(a2) # N: Revealed type is "__main__.A[builtins.int]"
22802280

22812281
[builtins fixtures/tuple.pyi]
22822282

2283+
[case testPostInitNotMethod]
2284+
def __post_init__() -> None:
2285+
pass
2286+
22832287
[case testPostInitCorrectSignature]
22842288
from typing import Any, Generic, TypeVar, Callable, Self
22852289
from dataclasses import dataclass, InitVar

0 commit comments

Comments
 (0)