Skip to content

Commit 1905071

Browse files
miss-islingtonserhiy-storchaka
andauthoredDec 5, 2021
bpo-45663: Fix is_dataclass() for dataclasses which are subclasses of types.GenericAlias (GH-29294)
(cherry picked from commit 446be16) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent 52a9a71 commit 1905071

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
@@ -1047,7 +1047,7 @@ def _is_dataclass_instance(obj):
10471047
def is_dataclass(obj):
10481048
"""Returns True if obj is a dataclass or an instance of a
10491049
dataclass."""
1050-
cls = obj if isinstance(obj, type) else type(obj)
1050+
cls = obj if isinstance(obj, type) and not isinstance(obj, GenericAlias) else type(obj)
10511051
return hasattr(cls, _FIELDS)
10521052

10531053

‎Lib/test/test_dataclasses.py

+12
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import pickle
88
import inspect
99
import builtins
10+
import types
1011
import unittest
1112
from unittest.mock import Mock
1213
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol
@@ -1348,6 +1349,17 @@ class B:
13481349
with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
13491350
replace(obj, x=0)
13501351

1352+
def test_is_dataclass_genericalias(self):
1353+
@dataclass
1354+
class A(types.GenericAlias):
1355+
origin: type
1356+
args: type
1357+
self.assertTrue(is_dataclass(A))
1358+
a = A(list, int)
1359+
self.assertTrue(is_dataclass(type(a)))
1360+
self.assertTrue(is_dataclass(a))
1361+
1362+
13511363
def test_helper_fields_with_class_instance(self):
13521364
# Check that we can call fields() on either a class or instance,
13531365
# 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)
Please sign in to comment.