Skip to content

Commit f72e4e5

Browse files
authored
Support optional for custom dataclass descriptors (#15628)
Fixes: #15020
1 parent ebfea94 commit f72e4e5

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

mypy/plugins/dataclasses.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -680,7 +680,8 @@ def collect_attributes(self) -> list[DataclassAttribute] | None:
680680
)
681681

682682
current_attr_names.add(lhs.name)
683-
init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt)
683+
with state.strict_optional_set(self._api.options.strict_optional):
684+
init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt)
684685
found_attrs[lhs.name] = DataclassAttribute(
685686
name=lhs.name,
686687
alias=alias,

test-data/unit/check-dataclass-transform.test

+4-3
Original file line numberDiff line numberDiff line change
@@ -1019,18 +1019,19 @@ class Desc:
10191019
def __get__(self, instance: object, owner: Any) -> str: ...
10201020
def __get__(self, instance, owner): ...
10211021

1022-
def __set__(self, instance: Any, value: bytes) -> None: ...
1022+
def __set__(self, instance: Any, value: bytes | None) -> None: ...
10231023

10241024
@my_dataclass
10251025
class C:
10261026
x: Desc
10271027

10281028
c = C(x=b'x')
1029-
C(x=1) # E: Argument "x" to "C" has incompatible type "int"; expected "bytes"
1029+
c = C(x=None)
1030+
C(x=1) # E: Argument "x" to "C" has incompatible type "int"; expected "Optional[bytes]"
10301031
reveal_type(c.x) # N: Revealed type is "builtins.str"
10311032
reveal_type(C.x) # N: Revealed type is "builtins.int"
10321033
c.x = b'x'
1033-
c.x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "bytes")
1034+
c.x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "Optional[bytes]")
10341035

10351036
[typing fixtures/typing-full.pyi]
10361037
[builtins fixtures/dataclasses.pyi]

0 commit comments

Comments
 (0)