-
Notifications
You must be signed in to change notification settings - Fork 37
Add Python PEP 613 and PEP 695 type alias support #467
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
Open
jbms
wants to merge
1
commit into
main
Choose a base branch
from
python-type-alias-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
113 changes: 113 additions & 0 deletions
113
sphinx_immaterial/apidoc/python/autodoc_type_alias_support.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| """Adds TypeAlias and TypeAliasType support to autodoc.""" | ||
|
|
||
| import ast | ||
| import sys | ||
| import typing | ||
| from typing import Any, TypeAlias, ClassVar | ||
|
|
||
| import sphinx | ||
|
|
||
| if sphinx.version_info < (7, 4): | ||
| raise ValueError("Sphinx >= 7.4 required for type alias support") | ||
|
|
||
| import sphinx.application | ||
| from sphinx.ext.autodoc import ( | ||
| Documenter, | ||
| DataDocumenter, | ||
| AttributeDocumenter, | ||
| ModuleDocumenter, | ||
| ) | ||
| import sphinx.util.typing | ||
| import sphinx.util.inspect | ||
| import sphinx.domains.python | ||
| from sphinx.pycode.parser import VariableCommentPicker | ||
| import typing_extensions | ||
|
|
||
| if sys.version_info >= (3, 12): | ||
| TYPE_ALIAS_TYPES = (typing.TypeAliasType, typing_extensions.TypeAliasType) | ||
| TYPE_ALIAS_AST_NODES = (ast.TypeAlias,) | ||
| else: | ||
| TYPE_ALIAS_TYPES = typing_extensions.TypeAliasType | ||
| TYPE_ALIAS_AST_NODES = () | ||
|
|
||
|
|
||
| class TypeAliasDocumenter(DataDocumenter): | ||
| priority = max(DataDocumenter.priority, AttributeDocumenter.priority) + 1 | ||
| objtype = "type" | ||
| option_spec: ClassVar[sphinx.util.typing.OptionSpec] = dict(Documenter.option_spec) | ||
| option_spec["no-value"] = DataDocumenter.option_spec["no-value"] | ||
|
|
||
| @classmethod | ||
| def can_document_member( | ||
| cls: type[Documenter], member: Any, membername: str, isattr: bool, parent: Any | ||
| ) -> bool: | ||
| if isinstance(member, TYPE_ALIAS_TYPES): | ||
| return True | ||
|
|
||
| if not isattr: | ||
| return False | ||
|
|
||
| type_hints = sphinx.util.typing.get_type_hints( | ||
| parent.object, include_extras=True | ||
| ) | ||
| return type_hints.get(membername) is TypeAlias | ||
|
|
||
| def add_directive_header(self, sig: str) -> None: | ||
| Documenter.add_directive_header(self, sig) | ||
| sourcename = self.get_sourcename() | ||
| try: | ||
| if self.options.no_value or self.should_suppress_value_header(): | ||
| pass | ||
| else: | ||
| value = self.object | ||
| if isinstance(value, TYPE_ALIAS_TYPES): | ||
| value = value.__value__ | ||
| objrepr = sphinx.util.typing.stringify_annotation(value) | ||
| self.add_line(" :canonical: " + objrepr, sourcename) | ||
| except ValueError: | ||
| pass | ||
|
|
||
|
|
||
| def _monkey_patch_sphinx_analyzer_to_support_type_aliases(): | ||
| orig_visit = VariableCommentPicker.visit | ||
|
|
||
| def visit(self, node: ast.AST) -> None: | ||
| if isinstance(node, TYPE_ALIAS_AST_NODES): | ||
| new_node = ast.Assign(targets=[node.name], value=node.value) | ||
| ast.copy_location(new_node, node) | ||
| ast.fix_missing_locations(new_node) | ||
| node = new_node | ||
| orig_visit(self, node) | ||
|
|
||
| VariableCommentPicker.visit = visit | ||
|
|
||
|
|
||
| def _monkey_patch_sphinx_pr_13926(): | ||
| # https://github.com/sphinx-doc/sphinx/pull/13926 | ||
|
|
||
| PyTypeAlias = sphinx.domains.python.PyTypeAlias | ||
|
|
||
| orig_add_target_and_index = PyTypeAlias.add_target_and_index | ||
|
|
||
| def add_target_and_index(self, name_cls, sig, signode) -> None: | ||
| saved_canonical = self.options.get("canonical", False) | ||
| try: | ||
| self.options.pop("canonical", None) | ||
| orig_add_target_and_index(self, name_cls, sig, signode) | ||
| finally: | ||
| if saved_canonical is not False: | ||
| self.options["canonical"] = saved_canonical | ||
|
|
||
| PyTypeAlias.add_target_and_index = add_target_and_index | ||
|
|
||
|
|
||
| _monkey_patch_sphinx_analyzer_to_support_type_aliases() | ||
| _monkey_patch_sphinx_pr_13926() | ||
|
|
||
|
|
||
| def setup(app: sphinx.application.Sphinx): | ||
| app.add_autodocumenter(TypeAliasDocumenter) | ||
| return { | ||
| "parallel_read_safe": True, | ||
| "parallel_write_safe": True, | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import typing | ||
|
|
||
|
|
||
| MyAlias: typing.TypeAlias = int | float | ||
| """PEP 613 type alias that can be int or float. | ||
|
|
||
| Group: | ||
| alias-group | ||
| """ | ||
|
|
||
|
|
||
| T = typing.TypeVar("T") | ||
| U = typing.TypeVar("U") | ||
|
|
||
| MyGenericAlias: typing.TypeAlias = list[T] | tuple[T, ...] | ||
| """My generic alias that can be a list or tuple with the given element type. | ||
|
|
||
| Group: | ||
| alias-group | ||
| """ | ||
|
|
||
|
|
||
| class Foo: | ||
| """Foo class.""" | ||
|
|
||
| MyMemberAlias: typing.TypeAlias = int | float | ||
| """PEP 613 alias within a class.""" | ||
|
|
||
| MyGenericMemberAlias: typing.TypeAlias = list[T] | tuple[U, ...] | ||
| """PEP 613 alias within a class.""" |
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Looks like mypy needs to be told to skip this file. Using Python v3.12+Using Python <= v3.11 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| type MyAliasType = int | float | ||
| """PEP 695 type alias that can be int or float. | ||
|
|
||
| Group: | ||
| alias-group | ||
| """ | ||
|
|
||
|
|
||
| type MyGenericAliasType[T] = list[T] | tuple[T, ...] | ||
| """PEP 695 type alias that can be a list or tuple with the given element type. | ||
|
|
||
| Group: | ||
| alias-group | ||
| """ | ||
|
|
||
|
|
||
| class Bar[T]: | ||
| """Class with PEP 695 type params.""" | ||
|
|
||
|
|
||
| class Foo: | ||
| """Foo class.""" | ||
|
|
||
| type MyMemberAlias = int | float | ||
| """PEP 613 alias within a class.""" | ||
|
|
||
| type MyGenericMemberAlias[T, U] = list[T] | tuple[U, ...] | ||
| """PEP 613 alias within a class.""" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should help ruff better understand how to format/lint that 1 file.