Skip to content

Commit 20b9062

Browse files
Fix issue with literal_eval
1 parent e5c78c0 commit 20b9062

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

src/mkdocstrings_handlers/python_xref/crossref.py

+14-3
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@
1515

1616
from __future__ import annotations
1717

18+
import ast
1819
import re
19-
from ast import literal_eval
20-
from typing import Callable, List, Optional, cast
20+
import sys
21+
from typing import Any, Callable, List, Optional, cast
2122

2223
from griffe import Docstring, Object
2324
from mkdocstrings import get_logger
@@ -353,7 +354,7 @@ def doc_value_offset_to_location(doc: Docstring, offset: int) -> tuple[int,int]:
353354
try:
354355
source = doc.source
355356
# compute docstring without cleaning up spaces and indentation
356-
rawvalue = str(literal_eval(source))
357+
rawvalue = str(safe_eval(source))
357358

358359
# adjust line offset by number of lines removed from front of docstring
359360
lineoffset += leading_space(rawvalue).count("\n")
@@ -388,3 +389,13 @@ def leading_space(s: str) -> str:
388389
if m := re.match(r"\s*", s):
389390
return m[0]
390391
return "" # pragma: no cover
392+
393+
if sys.version_info < (3, 10) or True:
394+
# TODO: remove when 3.9 support is dropped
395+
# In 3.9, literal_eval cannot handle comments in input
396+
def safe_eval(s: str) -> Any:
397+
"""Safely evaluate a string expression."""
398+
return eval(s) #eval(s, dict(__builtins__={}), {})
399+
else:
400+
save_eval = ast.literal_eval
401+

tests/test_crossref.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ def make_docstring_from_source(
204204
mod.lines_collection[filepath] = lines
205205
doc = Docstring(
206206
parent=mod,
207-
value=inspect.cleandoc(literal_eval(source)),
207+
value=inspect.cleandoc(eval(source)),
208208
lineno=lineno,
209209
endlineno=len(lines)
210210
)
@@ -235,6 +235,7 @@ def test_doc_value_offset_to_location() -> None:
235235
second
236236
third
237237
""" # a comment
238+
238239
# another comment
239240
'''
240241
).lstrip("\n"),

0 commit comments

Comments
 (0)