Skip to content

Commit

Permalink
Fix some
Browse files Browse the repository at this point in the history
  • Loading branch information
flying-sheep committed Oct 31, 2023
1 parent 56a1132 commit c4bc8c1
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
14 changes: 7 additions & 7 deletions src/scanpydoc/elegant_typehints/_formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
import inspect
from collections.abc import Callable, Iterable, Mapping, Sequence
from functools import partial
from typing import TYPE_CHECKING, Any, Literal, get_args, get_origin
from types import UnionType
from typing import TYPE_CHECKING, Any, Literal, Union, get_args, get_origin
from typing import Callable as t_Callable
from typing import Mapping as t_Mapping # noqa: UP035

from docutils import nodes
from docutils.parsers.rst.roles import set_classes
Expand Down Expand Up @@ -45,22 +48,19 @@ def _format_full(annotation: type[Any], config: Config) -> str | None:


def _format_terse(annotation: type[Any], config: Config) -> str:
from collections.abc import Mapping as t_Mapping
from typing import Union

origin = get_origin(annotation)
args = get_args(annotation)
tilde = "" if config.typehints_fully_qualified else "~"
fmt = partial(_format_terse, config=config)

# display `Union[A, B]` as `A | B`
if origin is Union:
if origin in (Union, UnionType):
# Never use the `Optional` keyword in the displayed docs.
# Use `| None` instead, similar to other large numerical packages.
return " | ".join(map(fmt, args))

# do not show the arguments of Mapping
if origin is Mapping or origin is t_Mapping:
if origin in (Mapping, t_Mapping):
return f":py:class:`{tilde}collections.abc.Mapping`"

# display dict as {k: v}
Expand All @@ -69,7 +69,7 @@ def _format_terse(annotation: type[Any], config: Config) -> str:
return f"{{{fmt(k)}: {fmt(v)}}}"

# display Callable[[a1, a2], r] as (a1, a2) -> r
if origin is Callable and len(args) == 2: # noqa: PLR2004
if origin in (Callable, t_Callable) and len(args) == 2: # noqa: PLR2004
params, ret = args
params = ["…"] if params is Ellipsis else map(fmt, params)
return f"({', '.join(params)}) → {fmt(ret)}"
Expand Down
2 changes: 1 addition & 1 deletion tests/test_elegant_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ class B:
(
tuple[Mapping[str, float], int],
r":annotation-terse:`:py:class:\`~collections.abc.Mapping\``\ "
r":annotation-full:`:py:class:\`~typing.Mapping\`\["
r":annotation-full:`:py:class:\`~collections.abc.Mapping\`\["
r":py:class:\`str\`, :py:class:\`float\`"
r"]`",
),
Expand Down

0 comments on commit c4bc8c1

Please sign in to comment.