bpo-45663: Fix is_dataclass() for dataclasses which are subclasses of… · python/cpython@446be16 (original) (raw)

3 files changed

lines changed

Original file line number Diff line number Diff line change
@@ -1211,7 +1211,7 @@ def _is_dataclass_instance(obj):
1211 1211 def is_dataclass(obj):
1212 1212 """Returns True if obj is a dataclass or an instance of a
1213 1213 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)
1215 1215 return hasattr(cls, _FIELDS)
1216 1216
1217 1217
Original file line number Diff line number Diff line change
@@ -8,6 +8,7 @@
8 8 import pickle
9 9 import inspect
10 10 import builtins
11 +import types
11 12 import unittest
12 13 from unittest.mock import Mock
13 14 from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol
@@ -1354,6 +1355,17 @@ class B:
1354 1355 with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'):
1355 1356 replace(obj, x=0)
1356 1357
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 +
1357 1369 def test_helper_fields_with_class_instance(self):
1358 1370 # Check that we can call fields() on either a class or instance,
1359 1371 # and get back the same thing.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
1 +Fix :func:`dataclasses.is_dataclass` for dataclasses which are subclasses of
2 +:class:`types.GenericAlias`.