Support optional for custom dataclass descriptors (#15628) Fixes: #15020
diff --git a/mypy/plugins/dataclasses.py b/mypy/plugins/dataclasses.py index 7b3795b..c78a1b3 100644 --- a/mypy/plugins/dataclasses.py +++ b/mypy/plugins/dataclasses.py
@@ -680,7 +680,8 @@ ) current_attr_names.add(lhs.name) - init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt) + with state.strict_optional_set(self._api.options.strict_optional): + init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt) found_attrs[lhs.name] = DataclassAttribute( name=lhs.name, alias=alias,
diff --git a/test-data/unit/check-dataclass-transform.test b/test-data/unit/check-dataclass-transform.test index 53a6eea..9029582 100644 --- a/test-data/unit/check-dataclass-transform.test +++ b/test-data/unit/check-dataclass-transform.test
@@ -1019,18 +1019,19 @@ def __get__(self, instance: object, owner: Any) -> str: ... def __get__(self, instance, owner): ... - def __set__(self, instance: Any, value: bytes) -> None: ... + def __set__(self, instance: Any, value: bytes | None) -> None: ... @my_dataclass class C: x: Desc c = C(x=b'x') -C(x=1) # E: Argument "x" to "C" has incompatible type "int"; expected "bytes" +c = C(x=None) +C(x=1) # E: Argument "x" to "C" has incompatible type "int"; expected "Optional[bytes]" reveal_type(c.x) # N: Revealed type is "builtins.str" reveal_type(C.x) # N: Revealed type is "builtins.int" c.x = b'x' -c.x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "bytes") +c.x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "Optional[bytes]") [typing fixtures/typing-full.pyi] [builtins fixtures/dataclasses.pyi]