Skip to content

Commit 1671e59

Browse files
committed
perf: LRU-cache parsing of type annotations in docstrings
1 parent 38464f2 commit 1671e59

1 file changed

Lines changed: 14 additions & 9 deletions

File tree

  • packages/griffelib/src/griffe/_internal/docstrings

‎packages/griffelib/src/griffe/_internal/docstrings/utils.py‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,10 @@
1818

1919
from __future__ import annotations
2020

21-
from ast import PyCF_ONLY_AST
21+
from ast import Expression, PyCF_ONLY_AST
2222
from contextlib import suppress
23-
from typing import TYPE_CHECKING
23+
from functools import lru_cache
24+
from typing import TYPE_CHECKING, cast
2425

2526
from griffe._internal.enumerations import LogLevel
2627
from griffe._internal.exceptions import BuiltinModuleError
@@ -64,6 +65,14 @@ def warn(docstring: Docstring, offset: int, message: str, log_level: LogLevel =
6465
warn(docstring, offset, message, log_level)
6566

6667

68+
@lru_cache(maxsize=512)
69+
def _compile_docstring_annotation(annotation: str) -> Expression | None:
70+
try:
71+
return cast("Expression", compile(annotation, mode="eval", filename="", flags=PyCF_ONLY_AST, optimize=2))
72+
except SyntaxError:
73+
return None
74+
75+
6776
def parse_docstring_annotation(
6877
annotation: str,
6978
docstring: Docstring,
@@ -80,14 +89,10 @@ def parse_docstring_annotation(
8089
Returns:
8190
The string unchanged, or a new name or expression.
8291
"""
83-
with suppress(
84-
AttributeError, # Docstring has no parent that can be used to resolve names.
85-
SyntaxError, # Annotation contains syntax errors.
86-
):
87-
code = compile(annotation, mode="eval", filename="", flags=PyCF_ONLY_AST, optimize=2)
88-
if code.body: # ty:ignore[unresolved-attribute]
92+
with suppress(AttributeError): # Docstring has no parent that can be used to resolve names.
93+
if (code := _compile_docstring_annotation(annotation)) and code.body:
8994
name_or_expr = safe_get_annotation(
90-
code.body, # ty:ignore[unresolved-attribute]
95+
code.body,
9196
parent=docstring.parent, # ty:ignore[invalid-argument-type]
9297
log_level=log_level,
9398
)

0 commit comments

Comments
 (0)