File tree Expand file tree Collapse file tree 2 files changed +21
-2
lines changed
Lib/test/test_dataclasses Expand file tree Collapse file tree 2 files changed +21
-2
lines changed Original file line number Diff line number Diff line change @@ -461,8 +461,9 @@ Module contents
461
461
462
462
.. function :: is_dataclass(obj)
463
463
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 ``.
466
467
467
468
If you need to know if a class is an instance of a dataclass (and
468
469
not a dataclass itself), then add a further check for ``not
Original file line number Diff line number Diff line change @@ -1524,6 +1524,24 @@ class A(types.GenericAlias):
1524
1524
self .assertTrue (is_dataclass (type (a )))
1525
1525
self .assertTrue (is_dataclass (a ))
1526
1526
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" )
1527
1545
1528
1546
def test_helper_fields_with_class_instance (self ):
1529
1547
# Check that we can call fields() on either a class or instance,
You can’t perform that action at this time.
0 commit comments