Skip to content

Commit

Permalink
Allow customizing warning category (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
flying-sheep authored Dec 7, 2023
1 parent 18eaa24 commit a9f9b15
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/legacy_api_wrap/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@

# The actual returned Callable of course accepts more positional parameters,
# but we want the type to lie so end users don’t rely on the deprecated API.
def legacy_api(*old_positionals: str) -> Callable[[Callable[P, R]], Callable[P, R]]:
def legacy_api(
*old_positionals: str,
category: type[Warning] = DeprecationWarning,
stacklevel: int = 2,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
"""Legacy API wrapper.
You want to change the API of a function:
Expand All @@ -54,6 +58,13 @@ def legacy_api(*old_positionals: str) -> Callable[[Callable[P, R]], Callable[P,
----------
old_positionals
The positional parameter names that the old function had after the new function’s ``*``.
category
The warning class to use for the deprecation.
Typically, you want to use ``DeprecationWarning``, ``PendingDeprecationWarning``,
``FutureWarning``, or a custom subclass of those.
stacklevel
The stacklevel to use for the deprecation warning.
By default, the first stack frame is the call site of the wrapped function.
"""

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

Expand Down
9 changes: 9 additions & 0 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,12 @@ def test_too_many_args() -> None:
match=r"new\(\) takes from 1 to 4 parameters, but 5 were given\.",
):
new(1, 2, 3, 4, 5) # type: ignore[misc]


def test_customize() -> None:
@legacy_api("a", category=FutureWarning)
def new(*, a: int) -> int:
return a

with pytest.raises(FutureWarning):
new(1) # type: ignore[misc]

0 comments on commit a9f9b15

Please sign in to comment.