Skip to content

Commit 0b5ffd3

Browse files
connesypawamoy
andauthored
fix: Parse deprecation message from expression arguments
Issue-4: #4 PR-5: #5 Co-authored-by: Timothée Mazzucotelli <[email protected]>
1 parent 7a5eb7c commit 0b5ffd3

File tree

2 files changed

+30
-7
lines changed

2 files changed

+30
-7
lines changed

src/griffe_warnings_deprecated/extension.py

+9-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22

33
from __future__ import annotations
44

5+
import ast
56
from typing import Any
67

7-
from griffe import Class, Docstring, DocstringSectionAdmonition, Extension, Function, get_logger
8+
from griffe import Class, Docstring, DocstringSectionAdmonition, ExprCall, Extension, Function, get_logger
89

910
logger = get_logger(__name__)
1011
self_namespace = "griffe_warnings_deprecated"
@@ -15,8 +16,13 @@
1516

1617
def _deprecated(obj: Class | Function) -> str | None:
1718
for decorator in obj.decorators:
18-
if decorator.callable_path in _decorators:
19-
return str(decorator.value).split("(", 1)[1].rstrip(")").rsplit(",", 1)[0].lstrip("f")[1:-1]
19+
if decorator.callable_path in _decorators and isinstance(decorator.value, ExprCall):
20+
first_arg = decorator.value.arguments[0]
21+
try:
22+
return ast.literal_eval(first_arg) # type: ignore[arg-type]
23+
except ValueError:
24+
logger.debug("%s is not a static string", str(first_arg))
25+
return None
2026
return None
2127

2228

tests/test_extension.py

+21-4
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import logging
56
from textwrap import dedent
67

78
import pytest
@@ -37,10 +38,6 @@ def hello(): ...
3738
def hello(): ...
3839
""",
3940
"""
40-
@warnings.deprecated(f"message", category=DeprecationWarning)
41-
def hello(): ...
42-
""",
43-
"""
4441
@warnings.deprecated("message", category=DeprecationWarning)
4542
def hello():
4643
'''Summary.'''
@@ -85,3 +82,23 @@ def test_extension(code: str) -> None:
8582
assert adm.title == "Deprecated"
8683
assert adm.value.kind == "danger"
8784
assert adm.value.contents == "message"
85+
86+
87+
def test_extension_fstring(caplog: pytest.LogCaptureFixture) -> None:
88+
"""Test the extension with an f-string as the deprecation message."""
89+
code = dedent(
90+
"""
91+
import warnings
92+
@warnings.deprecated(f"message")
93+
def hello(): ...
94+
""",
95+
)
96+
with (
97+
caplog.at_level(logging.DEBUG),
98+
temporary_visited_module(code, extensions=load_extensions(WarningsDeprecatedExtension)) as module,
99+
):
100+
adm = module["hello"].docstring
101+
102+
# Expect no deprecation message in the docstring.
103+
assert adm is None
104+
assert "f'message' is not a static string" in caplog.records[0].message

0 commit comments

Comments
 (0)