Skip to content

Commit 74ea978

Browse files
committed
Fix inferred type of is_dataclass(Any)
1 parent dc0b63f commit 74ea978

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

stdlib/@tests/test_cases/check_dataclasses.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,21 @@ class Foo:
4141
assert_type(f, Foo)
4242

4343

44+
def is_dataclass_any(arg: Any) -> None:
45+
if dc.is_dataclass(arg):
46+
assert_type(arg, DataclassInstance | type[DataclassInstance])
47+
48+
49+
def is_dataclass_object(arg: object) -> None:
50+
if dc.is_dataclass(arg):
51+
assert_type(arg, DataclassInstance | type[DataclassInstance])
52+
53+
54+
def is_dataclass_type(arg: type) -> None:
55+
if dc.is_dataclass(arg):
56+
assert_type(arg, type[DataclassInstance])
57+
58+
4459
def check_other_isdataclass_overloads(x: type, y: object) -> None:
4560
# TODO: pyright correctly emits an error on this, but mypy does not -- why?
4661
# dc.fields(x)

stdlib/dataclasses.pyi

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ from _typeshed import DataclassInstance
55
from builtins import type as Type # alias to avoid name clashes with fields named "type"
66
from collections.abc import Callable, Iterable, Mapping
77
from typing import Any, Generic, Literal, Protocol, TypeVar, overload
8-
from typing_extensions import TypeAlias, TypeIs
8+
from typing_extensions import Never, TypeAlias, TypeIs
99

1010
if sys.version_info >= (3, 9):
1111
from types import GenericAlias
@@ -213,6 +213,10 @@ else:
213213
) -> Any: ...
214214

215215
def fields(class_or_instance: DataclassInstance | type[DataclassInstance]) -> tuple[Field[Any], ...]: ...
216+
217+
# HACK: `obj: Never` typing matches if object argument is using `Any` type.
218+
@overload
219+
def is_dataclass(obj: Never) -> TypeIs[DataclassInstance | type[DataclassInstance]]: ... # type: ignore[narrowed-type-not-subtype] # pyright: ignore[reportGeneralTypeIssues]
216220
@overload
217221
def is_dataclass(obj: type) -> TypeIs[type[DataclassInstance]]: ...
218222
@overload

0 commit comments

Comments
 (0)