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

is_dataclass(Any) return type incorrect, differs from is_dataclass(object) #12401

Closed
intgr opened this issue Jul 22, 2024 · 7 comments · Fixed by #12517
Closed

is_dataclass(Any) return type incorrect, differs from is_dataclass(object) #12401

intgr opened this issue Jul 22, 2024 · 7 comments · Fixed by #12517

Comments

@intgr
Copy link
Contributor

intgr commented Jul 22, 2024

I found this surprising and arguably incorrect. According to mypy:

from typing import Any
from dataclasses import is_dataclass


def example1(arg: Any) -> None:
    if is_dataclass(arg):
        reveal_type(arg)  # ❌ Revealed type is "type[_typeshed.DataclassInstance]"


def example2(arg: object) -> None:
    if is_dataclass(arg):
        reveal_type(arg)  # ✅ Revealed type is "Union[_typeshed.DataclassInstance, type[_typeshed.DataclassInstance]]"

(Mypy playground)

This is because Any matches the 1st overload, even if 2nd overload with object argument is more appropriate for Any:

@overload
def is_dataclass(obj: type) -> TypeIs[type[DataclassInstance]]: ...
@overload
def is_dataclass(obj: object) -> TypeIs[DataclassInstance | type[DataclassInstance]]: ...

I couldn't think of an elegant fix for this.

@srittau
Copy link
Collaborator

srittau commented Jul 22, 2024

I don't think there is a fix, as Any is compatible with everything, so it will always match the first overload. Reordering is also not possible, at least not until we get a "Not" type (python/typing#801).

@intgr
Copy link
Contributor Author

intgr commented Jul 22, 2024

As a hack, we could add another overload case, with argument type that no real type ever satisfies but only Any can satisfy. Could we use the Never type?

@sobolevn
Copy link
Member

Refs python/mypy#17579

@srittau
Copy link
Collaborator

srittau commented Aug 7, 2024

@intgr We could try your suggestion in an experimental PR. (We should definitely add tests, though.) Otherwise I would close this issue as unfixable.

@intgr
Copy link
Contributor Author

intgr commented Aug 12, 2024

@sobolevn
Copy link
Member

MyPy PR is here: python/mypy#17678

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 a pull request may close this issue.

4 participants