8000 Clarify is_dataclass Behavior for Subclasses in Documentation and Tests · python/cpython@a319f3a · GitHub
[go: up one dir, main page]

Skip to content
Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit a319f3a

Browse files
committed
Clarify is_dataclass Behavior for Subclasses in Documentation and Tests
1 parent 0518edc commit a319f3a

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

Doc/library/dataclasses.rst

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -461,8 +461,9 @@ 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, an instance of a dataclass,
465+
or a subclass of a dataclass, otherwise return ``False``. Note that subclasses
466+
of dataclasses inherit the properties of the dataclass so will return ``True``.
466467

467468
If you need to know if a class is an instance of a dataclass (and
468469
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
@@ -1524,6 +1524,24 @@ class A(types.GenericAlias):
15241524
self.assertTrue(is_dataclass(type(a)))
15251525
self.assertTrue(is_dataclass(a))
15261526

1527+
def test_is_dataclass_for_subclass(self):
1528+
# Test to ensure that inheritance from a dataclass works correctly
1529+
# and that the subclass is also recognized as a dataclass.
1530+
@dataclass
1531+
class X:
1532+
y: int
1533+
1534+
class Z(X):
1535+
z: int = 0 # Adding a default field to demonstrate inheritance and dataclass behavior
1536+
1537+
# Check if X is a dataclass
1538+
self.assertTrue(is_dataclass(X), "X should be a dataclass")
1539+
# Check if Z is a dataclass, it should inherit the dataclass behavior from X
1540+
self.assertTrue(is_dataclass(Z), "Z should be a dataclass because it inherits from X")
1541+
# Create an instance of Z and check if the default values are set correctly
1542+
z_instance = Z(y=5)
1543+
self.assertEqual(z_instance.y, 5, "The value of y should be set to 5")
1544+
self.assertEqual(z_instance.z, 0, "The default value of z should be 0")
15271545

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

0 commit comments

Comments
 (0)
0