Skip to content

Commit 063f05b

Browse files
authored
Treat __dataclass_fields__ as ClassVar (#13721)
1 parent cd4bf12 commit 063f05b

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

mypy/plugins/dataclasses.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -593,6 +593,7 @@ def _add_dataclass_fields_magic_attribute(self) -> None:
593593
var = Var(name=attr_name, type=attr_type)
594594
var.info = self._ctx.cls.info
595595
var._fullname = self._ctx.cls.info.fullname + "." + attr_name
596+
var.is_classvar = True
596597
self._ctx.cls.info.names[attr_name] = SymbolTableNode(
597598
kind=MDEF, node=var, plugin_generated=True
598599
)

test-data/unit/check-dataclasses.test

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1819,10 +1819,10 @@ c.x # E: "C" has no attribute "x"
18191819
[case testDataclassCheckTypeVarBounds]
18201820
# flags: --python-version 3.7
18211821
from dataclasses import dataclass
1822-
from typing import Protocol, Dict, TypeVar, Generic
1822+
from typing import ClassVar, Protocol, Dict, TypeVar, Generic
18231823

18241824
class DataclassProtocol(Protocol):
1825-
__dataclass_fields__: Dict
1825+
__dataclass_fields__: ClassVar[Dict]
18261826

18271827
T = TypeVar("T", bound=DataclassProtocol)
18281828

@@ -1896,3 +1896,20 @@ FirstClass().FIRST_CONST = 42 # E: Cannot assign to final attribute "FIRST_CONS
18961896
reveal_type(SecondClass().SECOND_CONST) # N: Revealed type is "Literal[3]?"
18971897
SecondClass().SECOND_CONST = 42 # E: Cannot assign to final attribute "SECOND_CONST"
18981898
[builtins fixtures/dataclasses.pyi]
1899+
1900+
[case testDataclassFieldsProtocol]
1901+
# flags: --python-version 3.9
1902+
from dataclasses import dataclass
1903+
from typing import Any, Protocol
1904+
1905+
class ConfigProtocol(Protocol):
1906+
__dataclass_fields__: dict[str, Any]
1907+
1908+
def takes_cp(cp: ConfigProtocol): ...
1909+
1910+
@dataclass
1911+
class MyDataclass:
1912+
x: int = 3
1913+
1914+
takes_cp(MyDataclass)
1915+
[builtins fixtures/dataclasses.pyi]

test-data/unit/fine-grained.test

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9795,11 +9795,11 @@ class ExampleClass(Generic[T]):
97959795
[case testDataclassCheckTypeVarBoundsInReprocess]
97969796
# flags: --python-version 3.7
97979797
from dataclasses import dataclass
9798-
from typing import Protocol, Dict, TypeVar, Generic
9798+
from typing import ClassVar, Protocol, Dict, TypeVar, Generic
97999799
from m import x
98009800

98019801
class DataclassProtocol(Protocol):
9802-
__dataclass_fields__: Dict
9802+
__dataclass_fields__: ClassVar[Dict]
98039803

98049804
T = TypeVar("T", bound=DataclassProtocol)
98059805

0 commit comments

Comments
 (0)