bpo-45663: Fix is_dataclass() for dataclasses which are subclasses of types.GenericAlias (GH-29294)
(cherry picked from commit 446be166861b2f08f87f74018113dd98ca5fca02)
Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py
index fe4094b..105a95b 100644
--- a/Lib/dataclasses.py
+++ b/Lib/dataclasses.py
@@ -1211,7 +1211,7 @@
def is_dataclass(obj):
"""Returns True if obj is a dataclass or an instance of a
dataclass."""
- cls = obj if isinstance(obj, type) else type(obj)
+ cls = obj if isinstance(obj, type) and not isinstance(obj, GenericAlias) else type(obj)
return hasattr(cls, _FIELDS)
diff --git a/Lib/test/test_dataclasses.py b/Lib/test/test_dataclasses.py
index 47075df..ef5009a 100644
--- a/Lib/test/test_dataclasses.py
+++ b/Lib/test/test_dataclasses.py
@@ -8,6 +8,7 @@
import pickle
import inspect
import builtins
+import types
import unittest
from unittest.mock import Mock
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol
@@ -1354,6 +1355,17 @@
with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
replace(obj, x=0)
+ def test_is_dataclass_genericalias(self):
+ @dataclass
+ class A(types.GenericAlias):
+ origin: type
+ args: type
+ self.assertTrue(is_dataclass(A))
+ a = A(list, int)
+ self.assertTrue(is_dataclass(type(a)))
+ self.assertTrue(is_dataclass(a))
+
+
def test_helper_fields_with_class_instance(self):
# Check that we can call fields() on either a class or instance,
# and get back the same thing.
diff --git a/Misc/NEWS.d/next/Library/2021-10-28-23-11-59.bpo-45663.J90N5R.rst b/Misc/NEWS.d/next/Library/2021-10-28-23-11-59.bpo-45663.J90N5R.rst
new file mode 100644
index 0000000..f246f67
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2021-10-28-23-11-59.bpo-45663.J90N5R.rst
@@ -0,0 +1,2 @@
+Fix :func:`dataclasses.is_dataclass` for dataclasses which are subclasses of
+:class:`types.GenericAlias`.