Skip to content

Commit

Permalink
Treat __dataclass_fields__ as ClassVar (#13721)
Browse files Browse the repository at this point in the history
  • Loading branch information
hauntsaninja authored Sep 27, 2022
1 parent cd4bf12 commit 063f05b
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
1 change: 1 addition & 0 deletions mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,7 @@ def _add_dataclass_fields_magic_attribute(self) -> None:
var = Var(name=attr_name, type=attr_type)
var.info = self._ctx.cls.info
var._fullname = self._ctx.cls.info.fullname + "." + attr_name
var.is_classvar = True
self._ctx.cls.info.names[attr_name] = SymbolTableNode(
kind=MDEF, node=var, plugin_generated=True
)
Expand Down
21 changes: 19 additions & 2 deletions test-data/unit/check-dataclasses.test
Original file line number Diff line number Diff line change
Expand Up @@ -1819,10 +1819,10 @@ c.x # E: "C" has no attribute "x"
[case testDataclassCheckTypeVarBounds]
# flags: --python-version 3.7
from dataclasses import dataclass
from typing import Protocol, Dict, TypeVar, Generic
from typing import ClassVar, Protocol, Dict, TypeVar, Generic

class DataclassProtocol(Protocol):
__dataclass_fields__: Dict
__dataclass_fields__: ClassVar[Dict]

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

Expand Down Expand Up @@ -1896,3 +1896,20 @@ FirstClass().FIRST_CONST = 42 # E: Cannot assign to final attribute "FIRST_CONS
reveal_type(SecondClass().SECOND_CONST) # N: Revealed type is "Literal[3]?"
SecondClass().SECOND_CONST = 42 # E: Cannot assign to final attribute "SECOND_CONST"
[builtins fixtures/dataclasses.pyi]

[case testDataclassFieldsProtocol]
# flags: --python-version 3.9
from dataclasses import dataclass
from typing import Any, Protocol

class ConfigProtocol(Protocol):
__dataclass_fields__: dict[str, Any]

def takes_cp(cp: ConfigProtocol): ...

@dataclass
class MyDataclass:
x: int = 3

takes_cp(MyDataclass)
[builtins fixtures/dataclasses.pyi]
4 changes: 2 additions & 2 deletions test-data/unit/fine-grained.test
Original file line number Diff line number Diff line change
Expand Up @@ -9795,11 +9795,11 @@ class ExampleClass(Generic[T]):
[case testDataclassCheckTypeVarBoundsInReprocess]
# flags: --python-version 3.7
from dataclasses import dataclass
from typing import Protocol, Dict, TypeVar, Generic
from typing import ClassVar, Protocol, Dict, TypeVar, Generic
from m import x

class DataclassProtocol(Protocol):
__dataclass_fields__: Dict
__dataclass_fields__: ClassVar[Dict]

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

Expand Down

0 comments on commit 063f05b

Please sign in to comment.