Skip to content

Commit

Permalink
New stacklevel semantics, more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
JelleZijlstra committed Feb 6, 2023
1 parent d3e0bba commit 3d94110
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
37 changes: 37 additions & 0 deletions src/test_typing_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,43 @@ def b():
with self.assertWarnsRegex(DeprecationWarning, "b will go away soon"):
b()

def test_method(self):
class Capybara:
@deprecated("x will go away soon")
def x(self):
pass

instance = Capybara()
with self.assertWarnsRegex(DeprecationWarning, "x will go away soon"):
instance.x()

def test_property(self):
class Capybara:
@property
@deprecated("x will go away soon")
def x(self):
pass

@property
def no_more_setting(self):
return 42

@no_more_setting.setter
@deprecated("no more setting")
def no_more_setting(self, value):
pass

instance = Capybara()
with self.assertWarnsRegex(DeprecationWarning, "x will go away soon"):
instance.x

with warnings.catch_warnings():
warnings.simplefilter("error")
self.assertEqual(instance.no_more_setting, 42)

with self.assertWarnsRegex(DeprecationWarning, "no more setting"):
instance.no_more_setting = 42

def test_category(self):
@deprecated("c will go away soon", category=RuntimeWarning)
def c():
Expand Down
6 changes: 3 additions & 3 deletions src/typing_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2140,7 +2140,7 @@ def deprecated(
__msg: str,
*,
category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
stacklevel: int = 2,
stacklevel: int = 1,
) -> typing.Callable[[_T], _T]:
"""Indicate that a class, function or overload is deprecated.
Expand Down Expand Up @@ -2182,7 +2182,7 @@ def decorator(__arg: _T) -> _T:

@functools.wraps(original_new)
def __new__(cls, *args, **kwargs):
warnings.warn(__msg, category=category, stacklevel=stacklevel)
warnings.warn(__msg, category=category, stacklevel=stacklevel + 1)
# Mirrors a similar check in object.__new__.
if not has_init and (args or kwargs):
raise TypeError(f"{cls.__name__}() takes no arguments")
Expand All @@ -2197,7 +2197,7 @@ def __new__(cls, *args, **kwargs):
elif callable(__arg):
@functools.wraps(__arg)
def wrapper(*args, **kwargs):
warnings.warn(__msg, category=category, stacklevel=stacklevel)
warnings.warn(__msg, category=category, stacklevel=stacklevel + 1)
return __arg(*args, **kwargs)

__arg.__deprecated__ = wrapper.__deprecated__ = __msg
Expand Down

0 comments on commit 3d94110

Please sign in to comment.