Skip to content

Commit a9f9b15

Browse files
authored
Allow customizing warning category (#17)
1 parent 18eaa24 commit a9f9b15

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

src/legacy_api_wrap/__init__.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,11 @@
2929

3030
# The actual returned Callable of course accepts more positional parameters,
3131
# but we want the type to lie so end users don’t rely on the deprecated API.
32-
def legacy_api(*old_positionals: str) -> Callable[[Callable[P, R]], Callable[P, R]]:
32+
def legacy_api(
33+
*old_positionals: str,
34+
category: type[Warning] = DeprecationWarning,
35+
stacklevel: int = 2,
36+
) -> Callable[[Callable[P, R]], Callable[P, R]]:
3337
"""Legacy API wrapper.
3438
3539
You want to change the API of a function:
@@ -54,6 +58,13 @@ def legacy_api(*old_positionals: str) -> Callable[[Callable[P, R]], Callable[P,
5458
----------
5559
old_positionals
5660
The positional parameter names that the old function had after the new function’s ``*``.
61+
category
62+
The warning class to use for the deprecation.
63+
Typically, you want to use ``DeprecationWarning``, ``PendingDeprecationWarning``,
64+
``FutureWarning``, or a custom subclass of those.
65+
stacklevel
66+
The stacklevel to use for the deprecation warning.
67+
By default, the first stack frame is the call site of the wrapped function.
5768
"""
5869

5970
def wrapper(fn: Callable[P, R]) -> Callable[P, R]:
@@ -82,8 +93,8 @@ def fn_compatible(*args_all: P.args, **kw: P.kwargs) -> R:
8293
f"The specified parameters {old_positionals[:len(args_rest)]!r} are "
8394
"no longer positional. "
8495
f"Please specify them like `{old_positionals[0]}={args_rest[0]!r}`",
85-
DeprecationWarning,
86-
stacklevel=2,
96+
category=category,
97+
stacklevel=stacklevel,
8798
)
8899
kw_new: P.kwargs = {**kw, **dict(zip(old_positionals, args_rest))}
89100

tests/test_basic.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,12 @@ def test_too_many_args() -> None:
4141
match=r"new\(\) takes from 1 to 4 parameters, but 5 were given\.",
4242
):
4343
new(1, 2, 3, 4, 5) # type: ignore[misc]
44+
45+
46+
def test_customize() -> None:
47+
@legacy_api("a", category=FutureWarning)
48+
def new(*, a: int) -> int:
49+
return a
50+
51+
with pytest.raises(FutureWarning):
52+
new(1) # type: ignore[misc]

0 commit comments

Comments
 (0)