Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-128184: Fix display of signatures with ForwardRefs #130815

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1163,7 +1163,10 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen,
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', '')
text_sig = str(inspect.signature(
cls,
annotation_format=annotationlib.Format.FORWARDREF,
)).replace(' -> None', '')
except (TypeError, ValueError):
text_sig = ''
cls.__doc__ = (cls.__name__ + text_sig)
Expand Down
4 changes: 3 additions & 1 deletion Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@


import abc
from annotationlib import Format
from annotationlib import Format, ForwardRef
from annotationlib import get_annotations # re-exported
import ast
import dis
Expand Down Expand Up @@ -1342,6 +1342,8 @@ def repl(match):
if annotation.__module__ in ('builtins', base_module):
return annotation.__qualname__
return annotation.__module__+'.'+annotation.__qualname__
if isinstance(annotation, ForwardRef):
return annotation.__forward_arg__
return repr(annotation)

def formatannotationrelativeto(object):
Expand Down
26 changes: 26 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,31 @@ class C:

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

def test_docstring_undefined_name(self):
@dataclass
class C:
x: undef

self.assertDocStrEqual(C.__doc__, "C(x:undef)")

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, num: int) -> None: ...
""",
),
ns,
)

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

def test_docstring_with_no_signature(self):
# See https://github.com/python/cpython/issues/103449
class Meta(type):
Expand Down
9 changes: 9 additions & 0 deletions Lib/test/test_inspect/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1753,6 +1753,10 @@ def test_typing_replacement(self):
self.assertEqual(inspect.formatannotation(ann), 'Union[List[str], int]')
self.assertEqual(inspect.formatannotation(ann1), 'Union[List[testModule.typing.A], int]')

def test_forwardref(self):
fwdref = ForwardRef('fwdref')
self.assertEqual(inspect.formatannotation(fwdref), 'fwdref')


class TestIsMethodDescriptor(unittest.TestCase):

Expand Down Expand Up @@ -4587,6 +4591,11 @@ def foo(a: list[str]) -> Tuple[str, float]:
self.assertEqual(str(inspect.signature(foo)),
inspect.signature(foo).format())

def foo(x: undef):
pass
sig = inspect.signature(foo, annotation_format=Format.FORWARDREF)
self.assertEqual(str(sig), '(x: undef)')

def test_signature_str_positional_only(self):
P = inspect.Parameter
S = inspect.Signature
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Improve display of :class:`annotationlib.ForwardRef` object
within :class:`inspect.Signature` representations.
This also fixes a :exc:`NameError` that was raised when using
:func:`dataclasses.dataclass` on classes with unresolvable forward references.
Loading