[Python-checkins] gh-103449: Fix a bug in dataclass docstring generation (#103454)

carljm webhook-mailer at python.org
Mon Apr 17 19:33:36 EDT 2023


https://github.com/python/cpython/commit/b57f55c23e15654e9dd77680ff1462603e360b76
commit: b57f55c23e15654e9dd77680ff1462603e360b76
branch: main
author: Nikita Sobolev <mail at sobolevn.me>
committer: carljm <carl at oddbird.net>
date: 2023-04-17T17:33:22-06:00
summary:

gh-103449: Fix a bug in dataclass docstring generation (#103454)

files:
A Misc/NEWS.d/next/Library/2023-04-11-21-38-39.gh-issue-103449.-nxmhb.rst
M Lib/dataclasses.py
M Lib/test/test_dataclasses.py

diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py
index 4026c8b77975..a73cdc22a5f4 100644
--- a/Lib/dataclasses.py
+++ b/Lib/dataclasses.py
@@ -1128,8 +1128,13 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen,
 
     if not getattr(cls, '__doc__'):
         # Create a class doc-string.
-        cls.__doc__ = (cls.__name__ +
-                       str(inspect.signature(cls)).replace(' -> None', ''))
+        try:
+            # In some cases fetching a signature is not possible.
+            # But, we surely should not fail in this case.
+            text_sig = str(inspect.signature(cls)).replace(' -> None', '')
+        except (TypeError, ValueError):
+            text_sig = ''
+        cls.__doc__ = (cls.__name__ + text_sig)
 
     if match_args:
         # I could probably compute this once
diff --git a/Lib/test/test_dataclasses.py b/Lib/test/test_dataclasses.py
index 6888680105c4..ae8bfcc149e8 100644
--- a/Lib/test/test_dataclasses.py
+++ b/Lib/test/test_dataclasses.py
@@ -2297,6 +2297,19 @@ class C:
 
         self.assertDocStrEqual(C.__doc__, "C(x:collections.deque=<factory>)")
 
+    def test_docstring_with_no_signature(self):
+        # See https://github.com/python/cpython/issues/103449
+        class Meta(type):
+            __call__ = dict
+        class Base(metaclass=Meta):
+            pass
+
+        @dataclass
+        class C(Base):
+            pass
+
+        self.assertDocStrEqual(C.__doc__, "C")
+
 
 class TestInit(unittest.TestCase):
     def test_base_has_init(self):
diff --git a/Misc/NEWS.d/next/Library/2023-04-11-21-38-39.gh-issue-103449.-nxmhb.rst b/Misc/NEWS.d/next/Library/2023-04-11-21-38-39.gh-issue-103449.-nxmhb.rst
new file mode 100644
index 000000000000..0b2b47af1cba
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2023-04-11-21-38-39.gh-issue-103449.-nxmhb.rst
@@ -0,0 +1 @@
+Fix a bug in doc string generation in :func:`dataclasses.dataclass`.



More information about the Python-checkins mailing list