1818
1919from __future__ import annotations
2020
21- from ast import PyCF_ONLY_AST
21+ from ast import Expression , PyCF_ONLY_AST
2222from contextlib import suppress
23- from typing import TYPE_CHECKING
23+ from functools import lru_cache
24+ from typing import TYPE_CHECKING , cast
2425
2526from griffe ._internal .enumerations import LogLevel
2627from 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+
6776def 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