python / cpython

The Python programming language
https://www.python.org
Other
63.86k stars 30.56k forks source link

The builtin `help(...)` should unstringify (and "unforwardref") annotations #101552

Open SimpleArt opened 1 year ago

SimpleArt commented 1 year ago

Feature or enhancement

When using help(...), annotations should be unstringified and displayed without typing.ForwardRef.

Pitch

Current behavior displays string annotations with quotes as follows:

def foo(x: List["A"], y: "B") -> None:
    ...

help(foo)
"""
Help on function foo in module ...:

foo(x: List[ForwardRef('A')], y: 'B') -> None

"""

It should be fairly obvious how clunky this is to users, and that the desirable behavior should be something like:

help(foo)
"""
Help on function foo in module ...:

foo(x: List[A], y: B) -> None

"""

84171 is related, but whereas the suggestion there is to actually evaluate the annotations using typing.get_type_hints or similar, this proposal aims to only remove quotations and typing.ForwardRef(...) from the outputted documentation.

This means that the resulting documentation may not be 100% accurate but will not require evaluating the annotation, which can avoid issues such as annotations which cannot be evaluated for some reason.

For example:

import typing

if typing.TYPE_CHECKING:
    import numpy as np

def foo(x: "np.ndarray") -> None:
    ...

help(foo)
"""
Help on function foo in module ...:

foo(x: np.ndarray) -> None

"""

Note that the np.ndarray is not expanded out into its fully qualified name numpy.ndarray.

There are also some additional edge cases to consider, such as "ForwardRef('A')". Ideally this should be changed to A, but I don't think there's much impact if it is purposefully left as that, and leaving it as-is avoids other problems e.g. ForwardRef is not actually typing.ForwardRef in that example.

Linked PRs

JelleZijlstra commented 2 months ago

In Python 3.14, we can address this by using the STRING format for annotationlib.get_annotations. However, pydoc uses inspect.signature, and there's no way to pass the annotation format to inspect.signature.

So I'd like to add a format=Format.VALUE parameter to inspect.signature to support this use case. cc @larryhastings

carljm commented 2 months ago

So I'd like to add a format=Format.VALUE parameter to inspect.signature to support this use case

Perhaps the parameter should be named more explicitly (annotation_format), given that it's not a "format" for the entire signature, but rather for the annotations specifically.

JelleZijlstra commented 2 months ago

Yes, especially since there is also a Signature.format method that formats the entire signature.