Skip to content

Commit

Permalink
refactor: Run static analysis only after the whole package was loaded
Browse files Browse the repository at this point in the history
Issue #7: #7
PR #8: #8
  • Loading branch information
pawamoy authored Nov 14, 2023
1 parent c64bb73 commit 08be3d0
Show file tree
Hide file tree
Showing 7 changed files with 368 additions and 101 deletions.
10 changes: 10 additions & 0 deletions docs/examples.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
---
hide:
- navigation
---

# Examples

## Simple
Expand All @@ -16,6 +21,11 @@

## Enhanced

> WARNING: **Non-standard features**
The "enhanced" features are not part of PEP 727.
They just serve as an example to show what would be possible
if the PEP was enhanced to account for more use-cases.

/// details | `enhanced` Python module
type: example

Expand Down
42 changes: 19 additions & 23 deletions docs/examples/simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,11 @@ def other_parameters(


# Documenting yielded and received values, replacing Yields and Receives sections:
def generator() -> (
Generator[
Annotated[int, Doc("Yielded integers.")],
Annotated[int, Doc("Received integers.")],
Annotated[int, Doc("Final returned value.")],
]
):
def generator() -> Generator[
Annotated[int, Doc("Yielded integers.")],
Annotated[int, Doc("Received integers.")],
Annotated[int, Doc("Final returned value.")],
]:
"""Showing off generators."""


Expand All @@ -57,20 +55,18 @@ def iterator() -> Iterator[Annotated[int, Doc("Yielded integers.")]]:


# Advanced use-case: documenting multiple yielded/received/returned values:
def return_tuple() -> (
Generator[
tuple[
Annotated[int, Doc("First element of the yielded value.")],
Annotated[float, Doc("Second element of the yielded value.")],
],
tuple[
Annotated[int, Doc("First element of the received value.")],
Annotated[float, Doc("Second element of the received value.")],
],
tuple[
Annotated[int, Doc("First element of the returned value.")],
Annotated[float, Doc("Second element of the returned value.")],
],
]
):
def return_tuple() -> Generator[
tuple[
Annotated[int, Doc("First element of the yielded value.")],
Annotated[float, Doc("Second element of the yielded value.")],
],
tuple[
Annotated[int, Doc("First element of the received value.")],
Annotated[float, Doc("Second element of the received value.")],
],
tuple[
Annotated[int, Doc("First element of the returned value.")],
Annotated[float, Doc("Second element of the returned value.")],
],
]:
"""Showing off tuples as yield/receive/return values."""
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ classifiers = [
"Typing :: Typed",
]
dependencies = [
"griffe>=0.35",
"griffe>=0.38",
"typing-extensions>=4.7",
]

Expand Down
90 changes: 87 additions & 3 deletions src/griffe_typingdoc/_dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,16 @@

if TYPE_CHECKING:
from griffe import Attribute, Function, ObjectNode
from griffe.docstrings.dataclasses import DocstringSectionParameters
from griffe.docstrings.dataclasses import (
DocstringSectionAdmonition,
DocstringSectionOtherParameters,
DocstringSectionParameters,
DocstringSectionRaises,
DocstringSectionReceives,
DocstringSectionReturns,
DocstringSectionWarns,
DocstringSectionYields,
)


def _hints(node: ObjectNode) -> dict[str, str]:
Expand All @@ -29,15 +38,90 @@ def _doc(name: str, hints: dict[str, Any]) -> str | None:
return None


def _attribute_docs(node: ObjectNode, attr: Attribute) -> str:
def _attribute_docs(attr: Attribute, *, node: ObjectNode, **kwargs: Any) -> str: # noqa: ARG001
return _doc(attr.name, _hints(node)) or ""


def _parameters_docs(node: ObjectNode, func: Function) -> DocstringSectionParameters | None:
def _parameters_docs(
func: Function,
*,
node: ObjectNode,
**kwargs: Any, # noqa: ARG001
) -> DocstringSectionParameters | None:
hints = _hints(node)
params_doc: dict[str, dict[str, Any]] = {
name: {"description": _doc(name, hints)} for name in hints if name != "return"
}
if params_doc:
return _to_parameters_section(params_doc, func)
return None


# FIXME: Implement this function.
def _other_parameters_docs(
func: Function, # noqa: ARG001
*,
node: ObjectNode, # noqa: ARG001
**kwargs: Any, # noqa: ARG001
) -> DocstringSectionOtherParameters | None:
return None


# FIXME: Implement this function.
def _deprecated_docs(
attr_or_func: Attribute | Function, # noqa: ARG001
*,
node: ObjectNode, # noqa: ARG001
**kwargs: Any, # noqa: ARG001
) -> DocstringSectionAdmonition | None:
return None


# FIXME: Implement this function.
def _raises_docs(
attr_or_func: Attribute | Function, # noqa: ARG001
*,
node: ObjectNode, # noqa: ARG001
**kwargs: Any, # noqa: ARG001
) -> DocstringSectionRaises | None:
return None


# FIXME: Implement this function.
def _warns_docs(
attr_or_func: Attribute | Function, # noqa: ARG001
*,
node: ObjectNode, # noqa: ARG001
**kwargs: Any, # noqa: ARG001
) -> DocstringSectionWarns | None:
return None


# FIXME: Implement this function.
def _yields_docs(
func: Function, # noqa: ARG001
*,
node: ObjectNode, # noqa: ARG001
**kwargs: Any, # noqa: ARG001
) -> DocstringSectionYields | None:
return None


# FIXME: Implement this function.
def _receives_docs(
func: Function, # noqa: ARG001
*,
node: ObjectNode, # noqa: ARG001
**kwargs: Any, # noqa: ARG001
) -> DocstringSectionReceives | None:
return None


# FIXME: Implement this function.
def _returns_docs(
func: Function, # noqa: ARG001
*,
node: ObjectNode, # noqa: ARG001
**kwargs: Any, # noqa: ARG001
) -> DocstringSectionReturns | None:
return None
143 changes: 92 additions & 51 deletions src/griffe_typingdoc/_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,33 +11,28 @@
if TYPE_CHECKING:
import ast

from griffe.dataclasses import Attribute
from typing_extensions import Annotated, Doc # type: ignore[attr-defined]
from griffe.dataclasses import Attribute, Module, Object
from typing_extensions import Annotated, Doc


class TypingDocExtension(Extension):
"""Griffe extension that reads documentation from `typing.Doc`."""

def on_attribute_instance(
self,
*,
node: Annotated[
ast.AST | ObjectNode,
Doc("The object/AST node describing the attribute or its definition."),
],
attr: Annotated[
Attribute,
Doc("The Griffe attribute just instantiated."),
],
) -> None:
"""Post-process Griffe attributes to create their docstring."""
module = _dynamic if isinstance(node, ObjectNode) else _static
def __init__(self) -> None:
self._handled: set[str] = set()

def _handle_attribute(self, attr: Attribute, /, *, node: ObjectNode | None = None) -> None:
if attr.path in self._handled:
return
self._handled.add(attr.path)

module = _dynamic if node else _static

new_sections = (
docstring := module._attribute_docs(node, attr),
deprecated_section := module._deprecated_docs(node, attr),
raises_section := module._raises_docs(node, attr),
warns_section := module._warns_docs(node, attr),
docstring := module._attribute_docs(attr, node=node),
deprecated_section := module._deprecated_docs(attr, node=node),
raises_section := module._raises_docs(attr, node=node),
warns_section := module._warns_docs(attr, node=node),
)

if not any(new_sections):
Expand All @@ -48,45 +43,31 @@ def on_attribute_instance(

sections = attr.docstring.parsed

if deprecated_section := module._deprecated_docs(node, attr):
if deprecated_section:
sections.insert(0, deprecated_section)

if raises_section := module._raises_docs(node, attr):
if raises_section:
sections.append(raises_section)

if warns_section := module._warns_docs(node, attr):
if warns_section:
sections.append(warns_section)

def on_function_instance(
self,
*,
node: Annotated[
ast.AST | ObjectNode,
Doc("The object/AST node describing the function or its definition."),
],
func: Annotated[
Function,
Doc(
# Multiline docstring to test de-indentation.
"""
The Griffe function just instantiated.
""",
),
],
) -> None:
"""Post-process Griffe functions to add a parameters section."""
module = _dynamic if isinstance(node, ObjectNode) else _static
def _handle_function(self, func: Function, /, *, node: ObjectNode | None = None) -> None:
if func.path in self._handled:
return
self._handled.add(func.path)

module = _dynamic if node else _static

yields_section, receives_section, returns_section = module._yrr_docs(node, func)
new_sections = (
deprecated_section := module._deprecated_docs(node, func),
params_section := module._parameters_docs(node, func),
other_params_section := module._other_parameters_docs(node, func),
warns_section := module._warns_docs(node, func),
raises_section := module._raises_docs(node, func),
yields_section,
receives_section,
returns_section,
deprecated_section := module._deprecated_docs(func, node=node),
params_section := module._parameters_docs(func, node=node),
other_params_section := module._other_parameters_docs(func, node=node),
warns_section := module._warns_docs(func, node=node),
raises_section := module._raises_docs(func, node=node),
yields_section := module._yields_docs(func, node=node),
receives_section := module._receives_docs(func, node=node),
returns_section := module._returns_docs(func, node=node),
)

if not any(new_sections):
Expand Down Expand Up @@ -120,3 +101,63 @@ def on_function_instance(

if returns_section:
sections.append(returns_section)

def _handle_object(self, obj: Object) -> None:
if obj.is_alias:
return
if obj.is_module or obj.is_class:
for member in obj.members.values():
self._handle_object(member) # type: ignore[arg-type]
elif obj.is_function:
self._handle_function(obj) # type: ignore[arg-type]
elif obj.is_attribute:
self._handle_attribute(obj) # type: ignore[arg-type]

def on_package_loaded(
self,
*,
pkg: Annotated[
Module,
Doc("The top-level module representing a package."),
],
) -> None:
"""Post-process Griffe packages recursively (non-yet handled objects only)."""
self._handle_object(pkg)

def on_function_instance(
self,
*,
node: Annotated[
ast.AST | ObjectNode,
Doc("The object/AST node describing the function or its definition."),
],
func: Annotated[
Function,
Doc("""The Griffe function just instantiated."""),
],
) -> None:
"""Post-process Griffe functions to add a parameters section.
It applies only for dynamic analysis.
"""
if isinstance(node, ObjectNode):
self._handle_function(func, node=node)

def on_attribute_instance(
self,
*,
node: Annotated[
ast.AST | ObjectNode,
Doc("The object/AST node describing the attribute or its definition."),
],
attr: Annotated[
Attribute,
Doc("The Griffe attribute just instantiated."),
],
) -> None:
"""Post-process Griffe attributes to create their docstring.
It applies only for dynamic analysis.
"""
if isinstance(node, ObjectNode):
self._handle_attribute(attr, node=node)
Loading

0 comments on commit 08be3d0

Please sign in to comment.