Skip to content
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

Merged

Conversation

ikonst
Copy link
Contributor

@ikonst ikonst commented Aug 20, 2023

We already synthesize __dataclass_fields__ for all classes including @dataclass_transform'd ones, thus assume more than PEP-681 says. We might as well assume dataclasses.replace applies on all same classes. This way we risk false positive since it'll raise in runtime.

Fixes #15843.

@github-actions

This comment has been minimized.

@ikonst
Copy link
Contributor Author

ikonst commented Aug 24, 2023

@AlexWaygood WDYT?

Copy link
Member

@AlexWaygood AlexWaygood left a 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)

@ikonst
Copy link
Contributor Author

ikonst commented Aug 24, 2023

Thanks for explaining so thoroughly.

@ikonst
Copy link
Contributor Author

ikonst commented Aug 26, 2023

👉 #15962

@github-actions
Copy link
Contributor

github-actions bot commented Sep 5, 2023

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@ikonst
Copy link
Contributor Author

ikonst commented Sep 9, 2023

@AlexWaygood shall we go ahead with this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Custom dataclasses are not recognized as dataclasses
3 participants