-
-
Notifications
You must be signed in to change notification settings - Fork 109
Use format_annotation to render class attribute type annotations #299
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
41f4e4c
Use format_annotation to render class attribute type annotations
hoodmane 7f8cec8
Some cleanup
hoodmane 7d76b5b
Some more cleanup
hoodmane 87fab90
Some more cleanup
hoodmane 6ee4555
Use empty string for missing to make mypy happy
hoodmane cb2c700
Update some comments
hoodmane 4319d74
More cleanup
hoodmane 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| from functools import partial | ||
| from optparse import Values | ||
| from typing import Any, Tuple | ||
| from unittest.mock import patch | ||
|
|
||
| import sphinx.domains.python | ||
| import sphinx.ext.autodoc | ||
| from docutils.parsers.rst import Parser as RstParser | ||
| from docutils.utils import new_document | ||
| from sphinx.addnodes import desc_signature | ||
| from sphinx.application import Sphinx | ||
| from sphinx.domains.python import PyAttribute | ||
| from sphinx.ext.autodoc import AttributeDocumenter | ||
|
|
||
| # Defensively check for the things we want to patch | ||
| _parse_annotation = getattr(sphinx.domains.python, "_parse_annotation", None) | ||
|
|
||
| # We want to patch: | ||
| # * sphinx.ext.autodoc.stringify_typehint (in sphinx < 6.1) | ||
| # * sphinx.ext.autodoc.stringify_annotation (in sphinx >= 6.1) | ||
| STRINGIFY_PATCH_TARGET = "" | ||
| for target in ["stringify_typehint", "stringify_annotation"]: | ||
| if hasattr(sphinx.ext.autodoc, target): | ||
| STRINGIFY_PATCH_TARGET = f"sphinx.ext.autodoc.{target}" | ||
| break | ||
|
|
||
| # If we didn't locate both patch targets, we will just do nothing. | ||
| OKAY_TO_PATCH = bool(_parse_annotation and STRINGIFY_PATCH_TARGET) | ||
|
|
||
| # A label we inject to the type string so we know not to try to treat it as a | ||
| # type annotation | ||
| TYPE_IS_RST_LABEL = "--is-rst--" | ||
|
|
||
|
|
||
| orig_add_directive_header = AttributeDocumenter.add_directive_header | ||
| orig_handle_signature = PyAttribute.handle_signature | ||
|
|
||
|
|
||
| def stringify_annotation(app: Sphinx, annotation: Any, mode: str = "") -> str: # noqa: U100 | ||
| """Format the annotation with sphinx-autodoc-typehints and inject our | ||
| magic prefix to tell our patched PyAttribute.handle_signature to treat | ||
| it as rst.""" | ||
| from . import format_annotation | ||
|
|
||
| return TYPE_IS_RST_LABEL + format_annotation(annotation, app.config) | ||
|
|
||
|
|
||
| def patch_attribute_documenter(app: Sphinx) -> None: | ||
| """Instead of using stringify_typehint in | ||
| `AttributeDocumenter.add_directive_header`, use `format_annotation` | ||
| """ | ||
|
|
||
| def add_directive_header(*args: Any, **kwargs: Any) -> Any: | ||
| with patch(STRINGIFY_PATCH_TARGET, partial(stringify_annotation, app)): | ||
| return orig_add_directive_header(*args, **kwargs) | ||
|
|
||
| AttributeDocumenter.add_directive_header = add_directive_header # type:ignore[assignment] | ||
|
|
||
|
|
||
| def rst_to_docutils(settings: Values, rst: str) -> Any: | ||
| """Convert rst to a sequence of docutils nodes""" | ||
| doc = new_document("", settings) | ||
| RstParser().parse(rst, doc) | ||
| # Remove top level paragraph node so that there is no line break. | ||
| return doc.children[0].children | ||
|
|
||
|
|
||
| def patched_parse_annotation(settings: Values, typ: str, env: Any) -> Any: | ||
| # if typ doesn't start with our label, use original function | ||
| if not typ.startswith(TYPE_IS_RST_LABEL): | ||
| return _parse_annotation(typ, env) # type: ignore | ||
| # Otherwise handle as rst | ||
| typ = typ[len(TYPE_IS_RST_LABEL) :] | ||
| return rst_to_docutils(settings, typ) | ||
|
|
||
|
|
||
| def patched_handle_signature(self: PyAttribute, sig: str, signode: desc_signature) -> Tuple[str, str]: | ||
| target = "sphinx.domains.python._parse_annotation" | ||
| new_func = partial(patched_parse_annotation, self.state.document.settings) | ||
| with patch(target, new_func): | ||
| return orig_handle_signature(self, sig, signode) | ||
|
|
||
|
|
||
| def patch_attribute_handling(app: Sphinx) -> None: | ||
| """Use format_signature to format class attribute type annotations""" | ||
| if not OKAY_TO_PATCH: | ||
| return | ||
| PyAttribute.handle_signature = patched_handle_signature # type:ignore[assignment] | ||
| patch_attribute_documenter(app) | ||
|
|
||
|
|
||
| __all__ = ["patch_attribute_handling"] | ||
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
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.
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.
You could use none just need to annotation it
str | None, no?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.
That makes a type error when I try to use it unless I add an extra assert. Empty string is falsey and this makes the type checker happy without adding the assert.