1"""Helper functions for deprecation.
2
3This interface is itself unstable and may change without warning. Do
4not use these functions yourself, even as a joke. The underscores are
5there for a reason. No support will be given.
6
7In particular, most of this will go away without warning once
8Beautiful Soup drops support for Python 3.11, since Python 3.12
9defines a `@typing.deprecated()
10decorator. <https://peps.python.org/pep-0702/>`_
11"""
12
13import functools
14import warnings
15
16from typing import (
17 Any,
18 Callable,
19)
20
21
22def _deprecated_alias(old_name: str, new_name: str, version: str):
23 """Alias one attribute name to another for backward compatibility
24
25 :meta private:
26 """
27
28 @property
29 def alias(self) -> Any:
30 ":meta private:"
31 warnings.warn(
32 f"Access to deprecated property {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.",
33 DeprecationWarning,
34 stacklevel=2,
35 )
36 return getattr(self, new_name)
37
38 @alias.setter
39 def alias(self, value: str) -> None:
40 ":meta private:"
41 warnings.warn(
42 f"Write to deprecated property {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.",
43 DeprecationWarning,
44 stacklevel=2,
45 )
46 return setattr(self, new_name, value)
47
48 return alias
49
50
51def _deprecated_function_alias(
52 old_name: str, new_name: str, version: str
53) -> Callable[[Any], Any]:
54 def alias(self, *args: Any, **kwargs: Any) -> Any:
55 ":meta private:"
56 warnings.warn(
57 f"Call to deprecated method {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.",
58 DeprecationWarning,
59 stacklevel=2,
60 )
61 return getattr(self, new_name)(*args, **kwargs)
62
63 return alias
64
65
66def _deprecated(replaced_by: str, version: str) -> Callable:
67 def deprecate(func: Callable) -> Callable:
68 @functools.wraps(func)
69 def with_warning(*args: Any, **kwargs: Any) -> Any:
70 ":meta private:"
71 warnings.warn(
72 f"Call to deprecated method {func.__name__}. (Replaced by {replaced_by}) -- Deprecated since version {version}.",
73 DeprecationWarning,
74 stacklevel=2,
75 )
76 return func(*args, **kwargs)
77
78 return with_warning
79
80 return deprecate