bpo-45663: Fix is_dataclass() for dataclasses which are subclasses of… · python/cpython@1905071 (original) (raw)
3 files changed
lines changed
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1047,7 +1047,7 @@ def _is_dataclass_instance(obj): | ||
1047 | 1047 | def is_dataclass(obj): |
1048 | 1048 | """Returns True if obj is a dataclass or an instance of a |
1049 | 1049 | 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) | |
1051 | 1051 | return hasattr(cls, _FIELDS) |
1052 | 1052 | |
1053 | 1053 |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -7,6 +7,7 @@ | ||
7 | 7 | import pickle |
8 | 8 | import inspect |
9 | 9 | import builtins |
10 | +import types | |
10 | 11 | import unittest |
11 | 12 | from unittest.mock import Mock |
12 | 13 | from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol |
@@ -1348,6 +1349,17 @@ class B: | ||
1348 | 1349 | with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'): |
1349 | 1350 | replace(obj, x=0) |
1350 | 1351 | |
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 | + | |
1351 | 1363 | def test_helper_fields_with_class_instance(self): |
1352 | 1364 | # Check that we can call fields() on either a class or instance, |
1353 | 1365 | # 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`. |