Skip to content

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

Closed
@intgr

Description

@intgr

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions