Debian Codegraph @

src/trio/_deprecate.py

raw
1 from __future__ import annotations
2
3 import sys
4 import warnings
5 from functools import wraps
6 from typing import TYPE_CHECKING, ClassVar, TypeVar
7
8 import attrs
9
10 from ._util import final
11
12 if TYPE_CHECKING:
13 from collections.abc import Callable
14
15 from typing_extensions import ParamSpec
16
17 ArgsT = ParamSpec("ArgsT")
18
19 RetT = TypeVar("RetT")
20
21
22 # We want our warnings to be visible by default (at least for now), but we
23 # also want it to be possible to override that using the -W switch. AFAICT
24 # this means we cannot inherit from DeprecationWarning, because the only way
25 # to make it visible by default then would be to add our own filter at import
26 # time, but that would override -W switches...
27 class TrioDeprecationWarning(FutureWarning):
28 """Warning emitted if you use deprecated Trio functionality.
29
30 While a relatively mature project, Trio remains committed to refining its
31 design and improving usability. As part of this, we occasionally deprecate
32 or remove functionality that proves suboptimal. If you use Trio, we
33 recommend `subscribing to issue #1
34 <https://github.com/python-trio/trio/issues/1>`__ to get information about
35 upcoming deprecations and other backwards compatibility breaking changes.
36
37 Despite the name, this class currently inherits from
38 :class:`FutureWarning`, not :class:`DeprecationWarning`, because until a
39 1.0 release, we want these warnings to be visible by default. You can hide
40 them by installing a filter or with the ``-W`` switch: see the
41 :mod:`warnings` documentation for details.
42 """
43
44
45 def _url_for_issue(issue: int) -> str:
46 return f"https://github.com/python-trio/trio/issues/{issue}"
47
48
49 def _stringify(thing: object) -> str:
50 if hasattr(thing, "__module__") and hasattr(thing, "__qualname__"):
51 return f"{thing.__module__}.{thing.__qualname__}"
52 return str(thing)
53
54
55 def warn_deprecated(
56 thing: object,
57 version: str,
58 *,
59 issue: int | None,
60 instead: object,
61 stacklevel: int = 2,
62 use_triodeprecationwarning: bool = False,
63 ) -> None:
64 stacklevel += 1
65 msg = f"{_stringify(thing)} is deprecated since Trio {version}"
66 if instead is None:
67 msg += " with no replacement"
68 else:
69 msg += f"; use {_stringify(instead)} instead"
70 if issue is not None:
71 msg += f" ({_url_for_issue(issue)})"
72 if use_triodeprecationwarning:
73 warning_class: type[Warning] = TrioDeprecationWarning
74 else:
75 warning_class = DeprecationWarning
76 warnings.warn(warning_class(msg), stacklevel=stacklevel)
77
78
79 # @deprecated("0.2.0", issue=..., instead=...)
80 # def ...
81 def deprecated(
82 version: str,
83 *,
84 thing: object = None,
85 issue: int | None,
86 instead: object,
87 use_triodeprecationwarning: bool = False,
88 ) -> Callable[[Callable[ArgsT, RetT]], Callable[ArgsT, RetT]]:
89 def do_wrap(fn: Callable[ArgsT, RetT]) -> Callable[ArgsT, RetT]:
90 nonlocal thing
91
92 @wraps(fn)
93 def wrapper(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT:
94 warn_deprecated(
95 thing,
96 version,
97 instead=instead,
98 issue=issue,
99 use_triodeprecationwarning=use_triodeprecationwarning,
100 )
101 return fn(*args, **kwargs)
102
103 # If our __module__ or __qualname__ get modified, we want to pick up
104 # on that, so we read them off the wrapper object instead of the (now
105 # hidden) fn object
106 if thing is None:
107 thing = wrapper
108
109 if wrapper.__doc__ is not None:
110 doc = wrapper.__doc__
111 doc = doc.rstrip()
112 doc += "\n\n"
113 doc += f".. deprecated:: {version}\n"
114 if instead is not None:
115 doc += f" Use {_stringify(instead)} instead.\n"
116 if issue is not None:
117 doc += f" For details, see `issue #{issue} <{_url_for_issue(issue)}>`__.\n"
118 doc += "\n"
119 wrapper.__doc__ = doc
120
121 return wrapper
122
123 return do_wrap
124
125
126 def deprecated_alias(
127 old_qualname: str,
128 new_fn: Callable[ArgsT, RetT],
129 version: str,
130 *,
131 issue: int | None,
132 ) -> Callable[ArgsT, RetT]:
133 @deprecated(version, issue=issue, instead=new_fn)
134 @wraps(new_fn, assigned=("__module__", "__annotations__"))
135 def wrapper(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT:
136 """Deprecated alias."""
137 return new_fn(*args, **kwargs)
138
139 wrapper.__qualname__ = old_qualname
140 wrapper.__name__ = old_qualname.rpartition(".")[-1]
141 return wrapper
142
143
144 @final
145 @attrs.frozen(slots=False)
146 class DeprecatedAttribute:
147 _not_set: ClassVar[object] = object()
148
149 value: object
150 version: str
151 issue: int | None
152 instead: object = _not_set
153
154
155 def deprecate_attributes(
156 module_name: str, deprecated_attributes: dict[str, DeprecatedAttribute]
157 ) -> None:
158 def __getattr__(name: str) -> object:
159 if name in deprecated_attributes:
160 info = deprecated_attributes[name]
161 instead = info.instead
162 if instead is DeprecatedAttribute._not_set:
163 instead = info.value
164 thing = f"{module_name}.{name}"
165 warn_deprecated(thing, info.version, issue=info.issue, instead=instead)
166 return info.value
167
168 msg = "module '{}' has no attribute '{}'"
169 raise AttributeError(msg.format(module_name, name))
170
171 sys.modules[module_name].__getattr__ = __getattr__ # type: ignore[method-assign]