Skip to content

Commit 93e11d6

Browse files
committed
pythongh-104003: Implement PEP 702
1 parent 4b10ecc commit 93e11d6

File tree

2 files changed

+224
-1
lines changed

2 files changed

+224
-1
lines changed

Lib/test/test_typing.py

Lines changed: 147 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from typing import assert_type, cast, runtime_checkable
2424
from typing import get_type_hints
2525
from typing import get_origin, get_args
26-
from typing import override
26+
from typing import override, deprecated
2727
from typing import is_typeddict
2828
from typing import reveal_type
2929
from typing import dataclass_transform
@@ -4699,6 +4699,152 @@ def on_bottom(self, a: int) -> int:
46994699
self.assertTrue(instance.on_bottom.__override__)
47004700

47014701

4702+
class DeprecatedTests(BaseTestCase):
4703+
def test_dunder_deprecated(self):
4704+
@deprecated("A will go away soon")
4705+
class A:
4706+
pass
4707+
4708+
self.assertEqual(A.__deprecated__, "A will go away soon")
4709+
self.assertIsInstance(A, type)
4710+
4711+
@deprecated("b will go away soon")
4712+
def b():
4713+
pass
4714+
4715+
self.assertEqual(b.__deprecated__, "b will go away soon")
4716+
self.assertIsInstance(b, types.FunctionType)
4717+
4718+
@overload
4719+
@deprecated("no more ints")
4720+
def h(x: int) -> int: ...
4721+
@overload
4722+
def h(x: str) -> str: ...
4723+
def h(x):
4724+
return x
4725+
4726+
overloads = get_overloads(h)
4727+
self.assertEqual(len(overloads), 2)
4728+
self.assertEqual(overloads[0].__deprecated__, "no more ints")
4729+
4730+
def test_class(self):
4731+
@deprecated("A will go away soon")
4732+
class A:
4733+
pass
4734+
4735+
with self.assertWarnsRegex(DeprecationWarning, "A will go away soon"):
4736+
A()
4737+
with self.assertRaises(TypeError), self.assertWarnsRegex(DeprecationWarning, "A will go away soon"):
4738+
A(42)
4739+
4740+
@deprecated("HasInit will go away soon")
4741+
class HasInit:
4742+
def __init__(self, x):
4743+
self.x = x
4744+
4745+
with self.assertWarnsRegex(DeprecationWarning, "HasInit will go away soon"):
4746+
instance = HasInit(42)
4747+
self.assertEqual(instance.x, 42)
4748+
4749+
has_new_called = False
4750+
4751+
@deprecated("HasNew will go away soon")
4752+
class HasNew:
4753+
def __new__(cls, x):
4754+
nonlocal has_new_called
4755+
has_new_called = True
4756+
return super().__new__(cls)
4757+
4758+
def __init__(self, x) -> None:
4759+
self.x = x
4760+
4761+
with self.assertWarnsRegex(DeprecationWarning, "HasNew will go away soon"):
4762+
instance = HasNew(42)
4763+
self.assertEqual(instance.x, 42)
4764+
self.assertTrue(has_new_called)
4765+
new_base_called = False
4766+
4767+
class NewBase:
4768+
def __new__(cls, x):
4769+
nonlocal new_base_called
4770+
new_base_called = True
4771+
return super().__new__(cls)
4772+
4773+
def __init__(self, x) -> None:
4774+
self.x = x
4775+
4776+
@deprecated("HasInheritedNew will go away soon")
4777+
class HasInheritedNew(NewBase):
4778+
pass
4779+
4780+
with self.assertWarnsRegex(DeprecationWarning, "HasInheritedNew will go away soon"):
4781+
instance = HasInheritedNew(42)
4782+
self.assertEqual(instance.x, 42)
4783+
self.assertTrue(new_base_called)
4784+
4785+
def test_function(self):
4786+
@deprecated("b will go away soon")
4787+
def b():
4788+
pass
4789+
4790+
with self.assertWarnsRegex(DeprecationWarning, "b will go away soon"):
4791+
b()
4792+
4793+
def test_method(self):
4794+
class Capybara:
4795+
@deprecated("x will go away soon")
4796+
def x(self):
4797+
pass
4798+
4799+
instance = Capybara()
4800+
with self.assertWarnsRegex(DeprecationWarning, "x will go away soon"):
4801+
instance.x()
4802+
4803+
def test_property(self):
4804+
class Capybara:
4805+
@property
4806+
@deprecated("x will go away soon")
4807+
def x(self):
4808+
pass
4809+
4810+
@property
4811+
def no_more_setting(self):
4812+
return 42
4813+
4814+
@no_more_setting.setter
4815+
@deprecated("no more setting")
4816+
def no_more_setting(self, value):
4817+
pass
4818+
4819+
instance = Capybara()
4820+
with self.assertWarnsRegex(DeprecationWarning, "x will go away soon"):
4821+
instance.x
4822+
4823+
with warnings.catch_warnings():
4824+
warnings.simplefilter("error")
4825+
self.assertEqual(instance.no_more_setting, 42)
4826+
4827+
with self.assertWarnsRegex(DeprecationWarning, "no more setting"):
4828+
instance.no_more_setting = 42
4829+
4830+
def test_category(self):
4831+
@deprecated("c will go away soon", category=RuntimeWarning)
4832+
def c():
4833+
pass
4834+
4835+
with self.assertWarnsRegex(RuntimeWarning, "c will go away soon"):
4836+
c()
4837+
4838+
def test_turn_off_warnings(self):
4839+
@deprecated("d will go away soon", category=None)
4840+
def d():
4841+
pass
4842+
4843+
with warnings.catch_warnings():
4844+
warnings.simplefilter("error")
4845+
d()
4846+
4847+
47024848
class CastTests(BaseTestCase):
47034849

47044850
def test_basics(self):

Lib/typing.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ def _idfunc(_, x):
124124
'cast',
125125
'clear_overloads',
126126
'dataclass_transform',
127+
'deprecated',
127128
'final',
128129
'get_args',
129130
'get_origin',
@@ -3551,3 +3552,79 @@ def method(self) -> None:
35513552
# read-only property, TypeError if it's a builtin class.
35523553
pass
35533554
return method
3555+
3556+
3557+
def deprecated(
3558+
msg: str,
3559+
/,
3560+
*,
3561+
category: type[Warning] | None = DeprecationWarning,
3562+
stacklevel: int = 1,
3563+
) -> Callable[[T], T]:
3564+
"""Indicate that a class, function or overload is deprecated.
3565+
3566+
Usage:
3567+
3568+
@deprecated("Use B instead")
3569+
class A:
3570+
pass
3571+
3572+
@deprecated("Use g instead")
3573+
def f():
3574+
pass
3575+
3576+
@overload
3577+
@deprecated("int support is deprecated")
3578+
def g(x: int) -> int: ...
3579+
@overload
3580+
def g(x: str) -> int: ...
3581+
3582+
When this decorator is applied to an object, the type checker
3583+
will generate a diagnostic on usage of the deprecated object.
3584+
3585+
No runtime warning is issued. The decorator sets the ``__deprecated__``
3586+
attribute on the decorated object to the deprecation message
3587+
passed to the decorator. If applied to an overload, the decorator
3588+
must be after the ``@overload`` decorator for the attribute to
3589+
exist on the overload as returned by ``get_overloads()``.
3590+
3591+
See PEP 702 for details.
3592+
3593+
"""
3594+
def decorator(arg: T, /) -> T:
3595+
if category is None:
3596+
arg.__deprecated__ = msg
3597+
return arg
3598+
elif isinstance(arg, type):
3599+
original_new = arg.__new__
3600+
has_init = arg.__init__ is not object.__init__
3601+
3602+
@functools.wraps(original_new)
3603+
def __new__(cls, *args, **kwargs):
3604+
warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
3605+
# Mirrors a similar check in object.__new__.
3606+
if not has_init and (args or kwargs):
3607+
raise TypeError(f"{cls.__name__}() takes no arguments")
3608+
if original_new is not object.__new__:
3609+
return original_new(cls, *args, **kwargs)
3610+
else:
3611+
return original_new(cls)
3612+
3613+
arg.__new__ = staticmethod(__new__)
3614+
arg.__deprecated__ = __new__.__deprecated__ = msg
3615+
return arg
3616+
elif callable(arg):
3617+
@functools.wraps(arg)
3618+
def wrapper(*args, **kwargs):
3619+
warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
3620+
return arg(*args, **kwargs)
3621+
3622+
arg.__deprecated__ = wrapper.__deprecated__ = msg
3623+
return wrapper
3624+
else:
3625+
raise TypeError(
3626+
"@deprecated decorator with non-None category must be applied to "
3627+
f"a class or callable, not {arg!r}"
3628+
)
3629+
3630+
return decorator

0 commit comments

Comments
 (0)