-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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
dataclass.replace: allow transformed classes #15915
dataclass.replace: allow transformed classes #15915
Conversation
This comment has been minimized.
This comment has been minimized.
@AlexWaygood WDYT? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This makes sense to me, but I don't think it fixes the commented-out test in typeshed, which is trying to check that you can use is_dataclass
in a typeguard-y way, i.e.:
from dataclasses import is_dataclass, replace
def foo(x: object):
if is_dataclass(x) and not isinstance(x, type):
y = replace(x)
I think mypy is still going to complain about ^that kind of usage, but it's idiomatic code according to the dataclasses
documentation.
For reference, the signature that we have for is_dataclass
in typeshed is:
@overload
def is_dataclass(obj: DataclassInstance) -> Literal[True]: ...
@overload
def is_dataclass(obj: type) -> TypeGuard[type[DataclassInstance]]: ...
@overload
def is_dataclass(obj: object) -> TypeGuard[DataclassInstance | type[DataclassInstance]]: ...
And the signature we have for dataclasses.replace
is:
def replace(__obj: _DataclassT, **changes: Any) -> _DataclassT: ...
Where DataclassInstance
and _DataclassT
are:
class DataclassInstance(Protocol):
__dataclass_fields__: ClassVar[dict[str, dataclasses.Field[Any]]]
_DataclassT = TypeVar("_DataclassT", bound=DataclassInstance)
Thanks for explaining so thoroughly. |
👉 #15962 |
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
@AlexWaygood shall we go ahead with this? |
We already synthesize
__dataclass_fields__
for all classes including@dataclass_transform
'd ones, thus assume more than PEP-681 says. We might as well assumedataclasses.replace
applies on all same classes. This way we risk false positive since it'll raise in runtime.Fixes #15843.