Skip to content

Commit bf4ff3a

Browse files
adiaholiccarljm
andauthored
gh-119260: Clarify is_dataclass Behavior for Subclasses in Documentation and Tests (#119480)
Co-authored-by: Carl Meyer <[email protected]>
1 parent 0751511 commit bf4ff3a

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

Doc/library/dataclasses.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -461,8 +461,8 @@ Module contents
461461

462462
.. function:: is_dataclass(obj)
463463

464-
Return ``True`` if its parameter is a dataclass or an instance of one,
465-
otherwise return ``False``.
464+
Return ``True`` if its parameter is a dataclass (including subclasses of a
465+
dataclass) or an instance of one, otherwise return ``False``.
466466

467467
If you need to know if a class is an instance of a dataclass (and
468468
not a dataclass itself), then add a further check for ``not

Lib/test/test_dataclasses/__init__.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1547,6 +1547,24 @@ class A(types.GenericAlias):
15471547
self.assertTrue(is_dataclass(type(a)))
15481548
self.assertTrue(is_dataclass(a))
15491549

1550+
def test_is_dataclass_inheritance(self):
1551+
@dataclass
1552+
class X:
1553+
y: int
1554+
1555+
class Z(X):
1556+
pass
1557+
1558+
self.assertTrue(is_dataclass(X), "X should be a dataclass")
1559+
self.assertTrue(
1560+
is_dataclass(Z),
1561+
"Z should be a dataclass because it inherits from X",
1562+
)
1563+
z_instance = Z(y=5)
1564+
self.assertTrue(
1565+
is_dataclass(z_instance),
1566+
"z_instance should be a dataclass because it is an instance of Z",
1567+
)
15501568

15511569
def test_helper_fields_with_class_instance(self):
15521570
# Check that we can call fields() on either a class or instance,

0 commit comments

Comments
 (0)