Skip to content

Commit 446be16

Browse files
bpo-45663: Fix is_dataclass() for dataclasses which are subclasses of types.GenericAlias (GH-29294)
1 parent 1fd4de5 commit 446be16

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

Lib/dataclasses.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1211,7 +1211,7 @@ def _is_dataclass_instance(obj):
12111211
def is_dataclass(obj):
12121212
"""Returns True if obj is a dataclass or an instance of a
12131213
dataclass."""
1214-
cls = obj if isinstance(obj, type) else type(obj)
1214+
cls = obj if isinstance(obj, type) and not isinstance(obj, GenericAlias) else type(obj)
12151215
return hasattr(cls, _FIELDS)
12161216

12171217

Lib/test/test_dataclasses.py

+12
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import pickle
99
import inspect
1010
import builtins
11+
import types
1112
import unittest
1213
from unittest.mock import Mock
1314
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol
@@ -1354,6 +1355,17 @@ class B:
13541355
with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
13551356
replace(obj, x=0)
13561357

1358+
def test_is_dataclass_genericalias(self):
1359+
@dataclass
1360+
class A(types.GenericAlias):
1361+
origin: type
1362+
args: type
1363+
self.assertTrue(is_dataclass(A))
1364+
a = A(list, int)
1365+
self.assertTrue(is_dataclass(type(a)))
1366+
self.assertTrue(is_dataclass(a))
1367+
1368+
13571369
def test_helper_fields_with_class_instance(self):
13581370
# Check that we can call fields() on either a class or instance,
13591371
# and get back the same thing.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :func:`dataclasses.is_dataclass` for dataclasses which are subclasses of
2+
:class:`types.GenericAlias`.

0 commit comments

Comments
 (0)