diff options
author | Aditya Borikar <adityaborikar2@gmail.com> | 2024-05-29 17:26:22 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-05-29 17:26:22 (GMT) |
commit | bf4ff3ad2e362801e87c85fffd9e140b774cef26 (patch) | |
tree | e96d013843ab40077574be175ff614e6cfe46abb | |
parent | 0751511d24295c39fdf2f5b2255e3fa3d796ce4d (diff) | |
download | cpython-bf4ff3ad2e362801e87c85fffd9e140b774cef26.zip cpython-bf4ff3ad2e362801e87c85fffd9e140b774cef26.tar.gz cpython-bf4ff3ad2e362801e87c85fffd9e140b774cef26.tar.bz2 |
gh-119260: Clarify is_dataclass Behavior for Subclasses in Documentation and Tests (#119480)
Co-authored-by: Carl Meyer <carl@oddbird.net>
-rw-r--r-- | Doc/library/dataclasses.rst | 4 | ||||
-rw-r--r-- | Lib/test/test_dataclasses/__init__.py | 18 |
2 files changed, 20 insertions, 2 deletions
diff --git a/Doc/library/dataclasses.rst b/Doc/library/dataclasses.rst index cf707ca..fcb5e8b 100644 --- a/Doc/library/dataclasses.rst +++ b/Doc/library/dataclasses.rst @@ -461,8 +461,8 @@ Module contents .. function:: is_dataclass(obj) - Return ``True`` if its parameter is a dataclass or an instance of one, - otherwise return ``False``. + Return ``True`` if its parameter is a dataclass (including subclasses of a + dataclass) or an instance of one, otherwise return ``False``. If you need to know if a class is an instance of a dataclass (and not a dataclass itself), then add a further check for ``not diff --git a/Lib/test/test_dataclasses/__init__.py b/Lib/test/test_dataclasses/__init__.py index 04dd9f3..ffb8bbe 100644 --- a/Lib/test/test_dataclasses/__init__.py +++ b/Lib/test/test_dataclasses/__init__.py @@ -1547,6 +1547,24 @@ class TestCase(unittest.TestCase): self.assertTrue(is_dataclass(type(a))) self.assertTrue(is_dataclass(a)) + def test_is_dataclass_inheritance(self): + @dataclass + class X: + y: int + + class Z(X): + pass + + self.assertTrue(is_dataclass(X), "X should be a dataclass") + self.assertTrue( + is_dataclass(Z), + "Z should be a dataclass because it inherits from X", + ) + z_instance = Z(y=5) + self.assertTrue( + is_dataclass(z_instance), + "z_instance should be a dataclass because it is an instance of Z", + ) def test_helper_fields_with_class_instance(self): # Check that we can call fields() on either a class or instance, |