Skip to content

Commit

Permalink
Add support in documentation for type aliases using Python 3.12 `type…
Browse files Browse the repository at this point in the history
…` definition (#4044)
  • Loading branch information
chopan050 authored Dec 6, 2024
1 parent 263623e commit d485986
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions manim/utils/docbuild/module_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import ast
import sys
from pathlib import Path

from typing_extensions import TypeAlias
Expand Down Expand Up @@ -158,27 +159,35 @@ def parse_module_attributes() -> tuple[AliasDocsDict, DataDict, TypeVarDict]:
inner_nodes = [node]

for node in inner_nodes:
# If we encounter an assignment annotated as "TypeAlias":
if (
# Check if this node is a TypeAlias (type <name> = <value>)
# or an AnnAssign annotated as TypeAlias (<target>: TypeAlias = <value>).
is_type_alias = (
sys.version_info >= (3, 12) and type(node) is ast.TypeAlias
)
is_annotated_assignment_with_value = (
type(node) is ast.AnnAssign
and type(node.annotation) is ast.Name
and node.annotation.id == "TypeAlias"
and type(node.target) is ast.Name
and node.value is not None
):
alias_name = node.target.id
def_node = node.value
# If it's an Union, replace it with vertical bar notation
)
if is_type_alias or is_annotated_assignment_with_value:
alias_name = node.name.id if is_type_alias else node.target.id
definition_node = node.value

# If the definition is a Union, replace with vertical bar notation.
# Instead of "Union[Type1, Type2]", we'll have "Type1 | Type2".
if (
type(def_node) is ast.Subscript
and type(def_node.value) is ast.Name
and def_node.value.id == "Union"
type(definition_node) is ast.Subscript
and type(definition_node.value) is ast.Name
and definition_node.value.id == "Union"
):
union_elements = definition_node.slice.elts
definition = " | ".join(
ast.unparse(elem) for elem in def_node.slice.elts
ast.unparse(elem) for elem in union_elements
)
else:
definition = ast.unparse(def_node)
definition = ast.unparse(definition_node)

definition = definition.replace("npt.", "")
if category_dict is None:
Expand All @@ -188,7 +197,7 @@ def parse_module_attributes() -> tuple[AliasDocsDict, DataDict, TypeVarDict]:
alias_info = category_dict[alias_name]
continue

# Check if it is a typing.TypeVar
# Check if it is a typing.TypeVar (<target> = TypeVar(...)).
elif (
type(node) is ast.Assign
and type(node.targets[0]) is ast.Name
Expand Down

0 comments on commit d485986

Please sign in to comment.