Skip to content

Commit

Permalink
pythongh-128184: Fix docstring generation in dataclasses with forward…
Browse files Browse the repository at this point in the history
… refs
  • Loading branch information
sobolevn committed Dec 23, 2024
1 parent 180d417 commit 1d9d994
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1164,6 +1164,13 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen,
# 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 NameError:
# This means that some types where not defined, maybe due to
# forward references, etc. In this case, try different format.
text_sig = str(inspect.signature(
cls,
annotation_format=annotationlib.Format.STRING,
)).replace(" -> 'None'", '')
except (TypeError, ValueError):
text_sig = ''
cls.__doc__ = (cls.__name__ + text_sig)
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import types
import weakref
import traceback
import textwrap
import unittest
from unittest.mock import Mock
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict
Expand Down Expand Up @@ -2343,6 +2344,24 @@ class C:

self.assertDocStrEqual(C.__doc__, "C(x:collections.deque=<factory>)")

def test_docstring_with_unsolvable_forward_ref_in_init(self):
# See: https://github.com/python/cpython/issues/128184
ns = {}
exec(
textwrap.dedent(
"""
from dataclasses import dataclass
@dataclass
class C:
def __init__(self, x: X) -> None: ...
""",
),
ns,
)

self.assertDocStrEqual(ns['C'].__doc__, "C(x:'X')")

def test_docstring_with_no_signature(self):
# See https://github.com/python/cpython/issues/103449
class Meta(type):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixes :exc:`NameError` when using :func:`dataclasses.dataclass` on classes
with unresolvable forward references.

0 comments on commit 1d9d994

Please sign in to comment.