Skip to content

Support optional for custom dataclass descriptors #15628

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,8 @@ def collect_attributes(self) -> list[DataclassAttribute] | None:
)

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,
Expand Down
7 changes: 4 additions & 3 deletions test-data/unit/check-dataclass-transform.test
Original file line number Diff line number Diff line change
Expand Up @@ -1019,18 +1019,19 @@ class Desc:
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]
Expand Down