Skip to content

Commit

Permalink
Fix inferred type of is_dataclass(Any) (#12517)
Browse files Browse the repository at this point in the history
  • Loading branch information
intgr authored Aug 14, 2024
1 parent c03f07a commit 1ace571
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
15 changes: 15 additions & 0 deletions stdlib/@tests/test_cases/check_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,21 @@ class Foo:
assert_type(f, Foo)


def is_dataclass_any(arg: Any) -> None:
if dc.is_dataclass(arg):
assert_type(arg, Union["DataclassInstance", Type["DataclassInstance"]])


def is_dataclass_object(arg: object) -> None:
if dc.is_dataclass(arg):
assert_type(arg, Union["DataclassInstance", Type["DataclassInstance"]])


def is_dataclass_type(arg: type) -> None:
if dc.is_dataclass(arg):
assert_type(arg, Type["DataclassInstance"])


def check_other_isdataclass_overloads(x: type, y: object) -> None:
# TODO: pyright correctly emits an error on this, but mypy does not -- why?
# dc.fields(x)
Expand Down
6 changes: 5 additions & 1 deletion stdlib/dataclasses.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ from _typeshed import DataclassInstance
from builtins import type as Type # alias to avoid name clashes with fields named "type"
from collections.abc import Callable, Iterable, Mapping
from typing import Any, Generic, Literal, Protocol, TypeVar, overload
from typing_extensions import TypeAlias, TypeIs
from typing_extensions import Never, TypeAlias, TypeIs

if sys.version_info >= (3, 9):
from types import GenericAlias
Expand Down Expand Up @@ -213,6 +213,10 @@ else:
) -> Any: ...

def fields(class_or_instance: DataclassInstance | type[DataclassInstance]) -> tuple[Field[Any], ...]: ...

# HACK: `obj: Never` typing matches if object argument is using `Any` type.
@overload
def is_dataclass(obj: Never) -> TypeIs[DataclassInstance | type[DataclassInstance]]: ... # type: ignore[narrowed-type-not-subtype] # pyright: ignore[reportGeneralTypeIssues]
@overload
def is_dataclass(obj: type) -> TypeIs[type[DataclassInstance]]: ...
@overload
Expand Down

0 comments on commit 1ace571

Please sign in to comment.