Skip to content

Commit

Permalink
Support optional for custom dataclass descriptors (#15628)
Browse files Browse the repository at this point in the history
Fixes: #15020
  • Loading branch information
cdce8p authored Jul 9, 2023
1 parent ebfea94 commit f72e4e5
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
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

0 comments on commit f72e4e5

Please sign in to comment.