FaustDerLegende commited on
Commit
99d3cb0
·
verified ·
1 Parent(s): 50f724d

Upload folder using huggingface_hub (part 5)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +13 -0
  2. .venv/lib/python3.12/site-packages/deprecate/__pycache__/_types.cpython-312.pyc +0 -0
  3. .venv/lib/python3.12/site-packages/deprecate/__pycache__/audit.cpython-312.pyc +0 -0
  4. .venv/lib/python3.12/site-packages/deprecate/__pycache__/deprecation.cpython-312.pyc +3 -0
  5. .venv/lib/python3.12/site-packages/deprecate/__pycache__/proxy.cpython-312.pyc +0 -0
  6. .venv/lib/python3.12/site-packages/deprecate/__pycache__/utils.cpython-312.pyc +0 -0
  7. .venv/lib/python3.12/site-packages/deprecate/_cli.py +756 -0
  8. .venv/lib/python3.12/site-packages/deprecate/_pkg.py +348 -0
  9. .venv/lib/python3.12/site-packages/deprecate/_types.py +664 -0
  10. .venv/lib/python3.12/site-packages/deprecate/audit.py +1537 -0
  11. .venv/lib/python3.12/site-packages/deprecate/deprecation.py +0 -0
  12. .venv/lib/python3.12/site-packages/deprecate/docstring/__init__.py +9 -0
  13. .venv/lib/python3.12/site-packages/deprecate/docstring/__pycache__/__init__.cpython-312.pyc +0 -0
  14. .venv/lib/python3.12/site-packages/deprecate/docstring/__pycache__/griffe_ext.cpython-312.pyc +0 -0
  15. .venv/lib/python3.12/site-packages/deprecate/docstring/__pycache__/inject.cpython-312.pyc +0 -0
  16. .venv/lib/python3.12/site-packages/deprecate/docstring/__pycache__/sphinx_ext.cpython-312.pyc +0 -0
  17. .venv/lib/python3.12/site-packages/deprecate/docstring/griffe_ext.py +139 -0
  18. .venv/lib/python3.12/site-packages/deprecate/docstring/inject.py +626 -0
  19. .venv/lib/python3.12/site-packages/deprecate/docstring/sphinx_ext.py +154 -0
  20. .venv/lib/python3.12/site-packages/deprecate/proxy.py +1765 -0
  21. .venv/lib/python3.12/site-packages/deprecate/utils.py +355 -0
  22. .venv/lib/python3.12/site-packages/distutils-precedence.pth +3 -0
  23. .venv/lib/python3.12/site-packages/example.py +169 -0
  24. .venv/lib/python3.12/site-packages/filelock-3.32.3.dist-info/INSTALLER +1 -0
  25. .venv/lib/python3.12/site-packages/filelock-3.32.3.dist-info/METADATA +39 -0
  26. .venv/lib/python3.12/site-packages/filelock-3.32.3.dist-info/RECORD +48 -0
  27. .venv/lib/python3.12/site-packages/filelock-3.32.3.dist-info/WHEEL +4 -0
  28. .venv/lib/python3.12/site-packages/filelock-3.32.3.dist-info/licenses/LICENSE +21 -0
  29. .venv/lib/python3.12/site-packages/filelock/__init__.py +115 -0
  30. .venv/lib/python3.12/site-packages/filelock/__pycache__/__init__.cpython-312.pyc +0 -0
  31. .venv/lib/python3.12/site-packages/filelock/__pycache__/_api.cpython-312.pyc +0 -0
  32. .venv/lib/python3.12/site-packages/filelock/__pycache__/_async.cpython-312.pyc +0 -0
  33. .venv/lib/python3.12/site-packages/filelock/__pycache__/_async_read_write.cpython-312.pyc +0 -0
  34. .venv/lib/python3.12/site-packages/filelock/__pycache__/_descriptor.cpython-312.pyc +0 -0
  35. .venv/lib/python3.12/site-packages/filelock/__pycache__/_error.cpython-312.pyc +0 -0
  36. .venv/lib/python3.12/site-packages/filelock/__pycache__/_identity.cpython-312.pyc +0 -0
  37. .venv/lib/python3.12/site-packages/filelock/__pycache__/_lease.cpython-312.pyc +0 -0
  38. .venv/lib/python3.12/site-packages/filelock/__pycache__/_marker.cpython-312.pyc +0 -0
  39. .venv/lib/python3.12/site-packages/filelock/__pycache__/_read_write.cpython-312.pyc +0 -0
  40. .venv/lib/python3.12/site-packages/filelock/__pycache__/_soft.cpython-312.pyc +0 -0
  41. .venv/lib/python3.12/site-packages/filelock/__pycache__/_soft_protocol.cpython-312.pyc +0 -0
  42. .venv/lib/python3.12/site-packages/filelock/__pycache__/_strict.cpython-312.pyc +0 -0
  43. .venv/lib/python3.12/site-packages/filelock/__pycache__/_unix.cpython-312.pyc +0 -0
  44. .venv/lib/python3.12/site-packages/filelock/__pycache__/_util.cpython-312.pyc +0 -0
  45. .venv/lib/python3.12/site-packages/filelock/__pycache__/_windows.cpython-312.pyc +0 -0
  46. .venv/lib/python3.12/site-packages/filelock/__pycache__/asyncio.cpython-312.pyc +0 -0
  47. .venv/lib/python3.12/site-packages/filelock/__pycache__/version.cpython-312.pyc +0 -0
  48. .venv/lib/python3.12/site-packages/filelock/_api.py +1826 -0
  49. .venv/lib/python3.12/site-packages/filelock/_async.py +173 -0
  50. .venv/lib/python3.12/site-packages/filelock/_async_read_write.py +338 -0
.gitattributes CHANGED
@@ -151,3 +151,16 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
151
  .venv/lib/python3.12/site-packages/charset_normalizer/md.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
152
  .venv/lib/python3.12/site-packages/contourpy/_contourpy.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
153
  .venv/lib/python3.12/site-packages/cv2/cv2.abi3.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  .venv/lib/python3.12/site-packages/charset_normalizer/md.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
152
  .venv/lib/python3.12/site-packages/contourpy/_contourpy.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
153
  .venv/lib/python3.12/site-packages/cv2/cv2.abi3.so filter=lfs diff=lfs merge=lfs -text
154
+ .venv/lib/python3.12/site-packages/deprecate/__pycache__/deprecation.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
155
+ .venv/lib/python3.12/site-packages/fontTools/__pycache__/agl.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
156
+ .venv/lib/python3.12/site-packages/fontTools/cffLib/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
157
+ .venv/lib/python3.12/site-packages/fontTools/cu2qu/cu2qu.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
158
+ .venv/lib/python3.12/site-packages/fontTools/designspaceLib/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
159
+ .venv/lib/python3.12/site-packages/fontTools/feaLib/__pycache__/ast.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
160
+ .venv/lib/python3.12/site-packages/fontTools/feaLib/__pycache__/parser.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
161
+ .venv/lib/python3.12/site-packages/fontTools/feaLib/lexer.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
162
+ .venv/lib/python3.12/site-packages/fontTools/misc/bezierTools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
163
+ .venv/lib/python3.12/site-packages/fontTools/otlLib/__pycache__/builder.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
164
+ .venv/lib/python3.12/site-packages/fontTools/pens/momentsPen.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
165
+ .venv/lib/python3.12/site-packages/fontTools/qu2cu/qu2cu.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
166
+ .venv/lib/python3.12/site-packages/fontTools/subset/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/deprecate/__pycache__/_types.cpython-312.pyc ADDED
Binary file (38.9 kB). View file
 
.venv/lib/python3.12/site-packages/deprecate/__pycache__/audit.cpython-312.pyc ADDED
Binary file (72 kB). View file
 
.venv/lib/python3.12/site-packages/deprecate/__pycache__/deprecation.cpython-312.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d02b9b23d8f486a52d5ac16476672a23d5352cef60b5bf8e0c3638201814b39f
3
+ size 100575
.venv/lib/python3.12/site-packages/deprecate/__pycache__/proxy.cpython-312.pyc ADDED
Binary file (87.4 kB). View file
 
.venv/lib/python3.12/site-packages/deprecate/__pycache__/utils.cpython-312.pyc ADDED
Binary file (17.2 kB). View file
 
.venv/lib/python3.12/site-packages/deprecate/_cli.py ADDED
@@ -0,0 +1,756 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CLI entry point for pyDeprecate validation.
2
+
3
+ Provides two entry points for scanning Python code for misconfigured ``@deprecated`` wrappers:
4
+
5
+ - ``pydeprecate <subcommand> <path>`` — console script installed via ``pip install 'pyDeprecate[cli]'``
6
+ - ``python -m deprecate <subcommand> <path>`` — module invocation of the same CLI
7
+
8
+ Subcommands:
9
+ check — Validate wrapper configuration and flag misconfigured, chain-forming, or positional-only-arg wrappers.
10
+ expiry — Check for deprecated wrappers that have passed their scheduled ``remove_in`` deadline.
11
+ chains — Detect deprecated wrappers whose ``target`` is itself a deprecated callable.
12
+ all — Run all three checks in a single scan pass.
13
+ status — Render a markdown deprecation table to stdout (and optionally save it to a file).
14
+
15
+ """
16
+
17
+ import contextlib
18
+ import functools
19
+ import importlib.util
20
+ import sys
21
+ from collections.abc import Callable
22
+ from pathlib import Path
23
+ from typing import Any, Optional
24
+
25
+ from deprecate._pkg import (
26
+ _auto_detect_version,
27
+ _find_child_packages,
28
+ _is_package_dir,
29
+ _managed_sys_path,
30
+ _resolve_module_name,
31
+ _safe_module_name,
32
+ )
33
+ from deprecate.audit import (
34
+ DeprecationWrapperInfo,
35
+ TableStyle,
36
+ _check_expiry_for_callables,
37
+ find_deprecation_wrappers,
38
+ generate_deprecation_table,
39
+ validate_deprecation_chains,
40
+ validate_deprecation_expiry,
41
+ )
42
+
43
+
44
+ def _is_package_available(name: str) -> bool:
45
+ """Return True if *name* is importable without actually importing it."""
46
+ return importlib.util.find_spec(name) is not None
47
+
48
+
49
+ def _print(msg: str, *, stderr: bool = False) -> None:
50
+ """Print a message, using Rich console when available.
51
+
52
+ Routes output through :class:`~rich.console.Console` when the ``rich``
53
+ package is installed, falling back to built-in :func:`print` otherwise.
54
+
55
+ Args:
56
+ msg: The message to print.
57
+ stderr: If ``True``, send the message to *stderr* instead of *stdout*.
58
+
59
+ """
60
+ if _Reporter._HAS_RICH:
61
+ _Reporter._console(stderr).print(msg, markup=False, highlight=False)
62
+ else:
63
+ std_ = sys.stderr if stderr else sys.stdout
64
+ print(msg, file=std_)
65
+
66
+
67
+ def _scan_directory(path: str, include_members: bool = True) -> list[DeprecationWrapperInfo]:
68
+ """Scan a plain directory of top-level Python files.
69
+
70
+ Nested Python files in subdirectories are skipped unless they are part of an importable package layout. Plain
71
+ directories do not generally support dotted imports for nested modules, so this function only scans top-level
72
+ modules and warns when deeper files are present.
73
+
74
+ """
75
+ abs_path: Path = Path(path).resolve()
76
+ results: list[DeprecationWrapperInfo] = []
77
+
78
+ original_argv = sys.argv[:]
79
+ sys.argv = sys.argv[:1] # hide CLI args from any module-level code (e.g. setup.py)
80
+ try:
81
+ for entry in sorted(abs_path.iterdir(), key=lambda ent: ent.name):
82
+ if not (entry.is_file() and entry.suffix == ".py" and not entry.name.startswith("__")):
83
+ continue
84
+ module_name: str = entry.stem
85
+ try:
86
+ results.extend(find_deprecation_wrappers(module_name, recursive=False, include_members=include_members))
87
+ except SystemExit:
88
+ _print(f"Skipping {module_name}: module-level code exited (not a library module)", stderr=True)
89
+ except Exception as e:
90
+ _print(f"Could not scan {module_name}: {e}", stderr=True)
91
+ finally:
92
+ sys.argv = original_argv
93
+
94
+ nested_python_files_found: bool = any(
95
+ not fpy.name.startswith("__") for fpy in abs_path.rglob("*.py") if fpy.parent != abs_path
96
+ )
97
+
98
+ if nested_python_files_found:
99
+ _print(
100
+ "Skipping nested Python files in plain directory scan. Use an importable package layout with '__init__.py'"
101
+ " files, or scan an importable module/package path instead.",
102
+ stderr=True,
103
+ )
104
+ return results
105
+
106
+
107
+ def _scan_path(path: str, recursive: bool = True, include_members: bool = True) -> list[DeprecationWrapperInfo]:
108
+ """Scan a directory or importable module/package name for deprecated wrappers.
109
+
110
+ File paths are not accepted because ``find_deprecation_wrappers()`` expects an importable module or package name,
111
+ not a filesystem path.
112
+
113
+ """
114
+ pth: Path = Path(path)
115
+ if pth.is_dir():
116
+ if _is_package_dir(pth):
117
+ # package dir: resolve importable name from directory stem
118
+ return find_deprecation_wrappers(
119
+ Path(path).resolve().name, recursive=recursive, include_members=include_members
120
+ )
121
+ # Flat src-layout or project root: find package in direct children or src/ subdir.
122
+ child_pkgs = _find_child_packages(pth)
123
+ if len(child_pkgs) == 1:
124
+ return _scan_path(str(child_pkgs[0]), recursive=recursive, include_members=include_members)
125
+ return _scan_directory(path, include_members=include_members)
126
+ if pth.is_file():
127
+ raise ValueError(
128
+ f"File paths are not supported: {path!r}. Pass an importable module/package name or a directory instead."
129
+ )
130
+ return find_deprecation_wrappers(path, recursive=recursive, include_members=include_members)
131
+
132
+
133
+ # ---------------------------------------------------------------------------
134
+ # Reporter — all rich/plain dispatch in one namespace
135
+ # ---------------------------------------------------------------------------
136
+
137
+
138
+ class _Reporter:
139
+ _HAS_RICH: bool = _is_package_available("rich")
140
+ _out: Any = None
141
+ _err: Any = None
142
+ _rich_box: Any = None
143
+ _RichTable: Any = None
144
+
145
+ try:
146
+ from rich import box as _rich_box_import
147
+ from rich.console import Console as _RichConsole
148
+ from rich.table import Table as _RichTable_import
149
+
150
+ _rich_box = _rich_box_import
151
+ _RichTable = _RichTable_import
152
+ _out = _RichConsole()
153
+ _err = _RichConsole(stderr=True)
154
+ except ImportError: # pragma: no cover
155
+ pass
156
+
157
+ @staticmethod
158
+ def _console(stderr: bool = False) -> Any: # noqa: ANN401
159
+ """Return the Rich Console for stdout (default) or stderr."""
160
+ return _Reporter._err if stderr else _Reporter._out
161
+
162
+ @staticmethod
163
+ def _make_table(title: str, col: str, *, title_style: str, col_style: str) -> Any: # noqa: ANN401
164
+ """Build a three-column Module/Function/<col> Rich table."""
165
+ table = _Reporter._RichTable(title=title, box=_Reporter._rich_box.ROUNDED, title_style=title_style)
166
+ table.add_column("Module", style="cyan")
167
+ table.add_column("Function", style="magenta")
168
+ table.add_column(col, style=col_style)
169
+ return table
170
+
171
+ @staticmethod
172
+ def _render_table(
173
+ title: str,
174
+ col: str,
175
+ *,
176
+ title_style: str,
177
+ col_style: str,
178
+ rows: list[tuple[str, ...]],
179
+ plain_prefix: str,
180
+ ) -> None:
181
+ """Render a three-column Module/Function/Detail table (rich or plain fallback)."""
182
+ if _Reporter._HAS_RICH:
183
+ table = _Reporter._make_table(title, col, title_style=title_style, col_style=col_style)
184
+ for row in rows:
185
+ table.add_row(*row)
186
+ _Reporter._console().print(table)
187
+ else:
188
+ _print(f"\n{plain_prefix}")
189
+ for mod, fn, detail in rows:
190
+ _print(f"\t- {mod}.{fn}: {detail}")
191
+
192
+ @staticmethod
193
+ def invalid_args(items: list[DeprecationWrapperInfo]) -> None:
194
+ """Report wrappers with invalid ``args_mapping`` keys."""
195
+ _Reporter._render_table(
196
+ "Invalid Argument Mappings",
197
+ "Invalid Args",
198
+ title_style="bold red",
199
+ col_style="red",
200
+ rows=[(r.module, r.function, ", ".join(r.invalid_args)) for r in items],
201
+ plain_prefix="[ERROR] Found functions with invalid argument mappings:",
202
+ )
203
+
204
+ @staticmethod
205
+ def identity_args_mappings(items: list[DeprecationWrapperInfo]) -> None:
206
+ """Report wrappers whose ``args_mapping`` maps an argument to itself."""
207
+ _Reporter._render_table(
208
+ "Identity Argument Mappings (arg -> arg)",
209
+ "Identity Args",
210
+ title_style="bold yellow",
211
+ col_style="yellow",
212
+ rows=[(r.module, r.function, ", ".join(r.identity_args_mapping)) for r in items],
213
+ plain_prefix="[WARNING] Found functions with identity argument mappings (arg -> arg):",
214
+ )
215
+
216
+ @staticmethod
217
+ def no_effect(items: list[DeprecationWrapperInfo]) -> None:
218
+ """Report wrappers that have no observable effect on callers."""
219
+
220
+ def _reasons(r: DeprecationWrapperInfo) -> str:
221
+ """Format the no-effect reasons for a single wrapper as a comma-separated string."""
222
+ parts = []
223
+ if r.empty_args_mapping:
224
+ parts.append("Empty mapping")
225
+ if r.self_reference:
226
+ parts.append("Self reference")
227
+ if r.all_identity:
228
+ parts.append("All identity mappings")
229
+ return ", ".join(parts)
230
+
231
+ _Reporter._render_table(
232
+ "No-Effect Wrappers (zero impact)",
233
+ "Reason",
234
+ title_style="bold yellow",
235
+ col_style="yellow",
236
+ rows=[(r.module, r.function, _reasons(r)) for r in items],
237
+ plain_prefix="[WARNING] Found deprecated wrappers with NO EFFECT (zero impact):",
238
+ )
239
+
240
+ @staticmethod
241
+ def chains(items: list[DeprecationWrapperInfo], *, error: bool = False) -> None:
242
+ """Report deprecated-to-deprecated forwarding chains; ``error=True`` renders in red."""
243
+ style = "bold red" if error else "bold yellow"
244
+ col_style = "red" if error else "yellow"
245
+ prefix = "[ERROR]" if error else "[WARNING]"
246
+ _Reporter._render_table(
247
+ "Deprecation Chains",
248
+ "Chain Type",
249
+ title_style=style,
250
+ col_style=col_style,
251
+ rows=[(r.module, r.function, r.chain_type.value if r.chain_type is not None else "") for r in items],
252
+ plain_prefix=f"{prefix} Found deprecated wrappers forming deprecation chains:",
253
+ )
254
+
255
+ @staticmethod
256
+ def expiry(expired: list[str]) -> None:
257
+ """Report deprecated wrappers that have passed their ``remove_in`` deadline."""
258
+ if _Reporter._HAS_RICH:
259
+ table = _Reporter._RichTable(
260
+ title="Expired Deprecated Wrappers", box=_Reporter._rich_box.ROUNDED, title_style="bold red"
261
+ )
262
+ table.add_column("Message", style="red")
263
+ for msg in expired:
264
+ table.add_row(msg)
265
+ _Reporter._console().print(table)
266
+ else:
267
+ _print("\n[ERROR] Found expired deprecated wrappers:")
268
+ for msg in expired:
269
+ _print(f"\t- {msg}")
270
+
271
+ @staticmethod
272
+ def positional_only_args(items: list[DeprecationWrapperInfo]) -> None:
273
+ """Report wrappers whose ``args_mapping`` remaps a kwarg to a POSITIONAL_ONLY constructor parameter."""
274
+ _Reporter._render_table(
275
+ "Positional-Only Constructor Args in args_mapping",
276
+ "Positional-Only Args",
277
+ title_style="bold yellow",
278
+ col_style="yellow",
279
+ rows=[(r.module, r.function, ", ".join(r.args_mapping_positional_only)) for r in items],
280
+ plain_prefix=(
281
+ "[WARNING] Found args_mapping entries targeting POSITIONAL_ONLY constructor parameters"
282
+ " (proxy falls back to setattr for these entries):"
283
+ ),
284
+ )
285
+
286
+ @staticmethod
287
+ def issues(results: list[DeprecationWrapperInfo], *, error_on_chains: bool = False) -> bool:
288
+ """Print categorised diagnostics and return whether any issues were found."""
289
+ invalid_args = [r for r in results if r.invalid_args]
290
+ identity_args_mappings = [r for r in results if r.identity_args_mapping]
291
+ no_effect = [r for r in results if r.no_effect]
292
+ chains = [r for r in results if r.chain_type is not None]
293
+ positional_only = [r for r in results if r.args_mapping_positional_only]
294
+
295
+ if not (invalid_args or identity_args_mappings or no_effect or chains or positional_only):
296
+ return False
297
+
298
+ if invalid_args:
299
+ _Reporter.invalid_args(invalid_args)
300
+ if identity_args_mappings:
301
+ _Reporter.identity_args_mappings(identity_args_mappings)
302
+ if no_effect:
303
+ _Reporter.no_effect(no_effect)
304
+ if chains:
305
+ _Reporter.chains(chains, error=error_on_chains)
306
+ if positional_only:
307
+ _Reporter.positional_only_args(positional_only)
308
+
309
+ return True
310
+
311
+
312
+ def _do_expiry(path: str, version: Optional[str], recursive: bool) -> Optional[list[str]]:
313
+ """Run the expiry scan and return expired wrapper messages, or None when packaging is unavailable.
314
+
315
+ Caller is responsible for setting up ``sys.path`` via :func:`_managed_sys_path` before calling.
316
+
317
+ Args:
318
+ path: Package directory path or importable module name string.
319
+ version: Current package version for comparison, or None to auto-detect.
320
+ recursive: Scan submodules recursively.
321
+
322
+ Returns:
323
+ List of expired wrapper message strings (may be empty), or None when the
324
+ ``packaging`` library is unavailable (advisory — warning already printed to stderr).
325
+
326
+ """
327
+ module_name = _resolve_module_name(path)
328
+ try:
329
+ return validate_deprecation_expiry(module_name, version, recursive=recursive)
330
+ except ImportError as exc:
331
+ if _is_missing_packaging_import_error(exc):
332
+ _print(
333
+ "The 'expiry' subcommand requires the 'packaging' library.\n"
334
+ "Install it with: `pip install 'pyDeprecate[audit]'`",
335
+ stderr=True,
336
+ )
337
+ return None
338
+ if getattr(exc, "name", None) is not None:
339
+ # Python's import system sets ``exc.name`` when a module-level ``import`` statement
340
+ # fails — this is a broken import inside the user's package, not a version-detection
341
+ # failure. Propagate so the caller gets the real error instead of the misleading
342
+ # "Could not determine version" message.
343
+ raise
344
+ _print(
345
+ "Could not determine the current package version automatically.\n"
346
+ "Pass --version explicitly, or ensure the package is installed and importable.\n\n"
347
+ f"Original error: {exc}",
348
+ stderr=True,
349
+ )
350
+ return None
351
+ # other exceptions propagate to cli()'s top-level handler around fire.Fire
352
+
353
+
354
+ def _is_missing_packaging_import_error(error: ImportError) -> bool:
355
+ """Return True when an ImportError was caused by a missing packaging dependency.
356
+
357
+ Args:
358
+ error: The ImportError raised while trying to inspect expiry information.
359
+
360
+ Returns:
361
+ True if the error indicates that the ``packaging`` library is unavailable.
362
+
363
+ """
364
+ for exc in (error, getattr(error, "__cause__", None)):
365
+ if exc is None:
366
+ continue
367
+ name = getattr(exc, "name", None)
368
+ if isinstance(name, str) and (name == "packaging" or name.startswith("packaging.")):
369
+ return True
370
+ return "No module named 'packaging'" in str(error)
371
+
372
+
373
+ # ---------------------------------------------------------------------------
374
+ # Subcommand functions
375
+ # ---------------------------------------------------------------------------
376
+
377
+
378
+ def _print_scan_header(path: str, version: Optional[str] = None, *, user_provided: bool = False) -> None:
379
+ """Print a consistent scan header: scanning location, package name, and version."""
380
+ module = _safe_module_name(path)
381
+ _print(f"Scanning: {path}")
382
+ if version is not None:
383
+ source = "user-provided" if user_provided else "auto-detected"
384
+ _print(f"Package: {module} Version: {version} ({source})")
385
+ else:
386
+ _print(f"Package: {module}")
387
+
388
+
389
+ def cmd_check(
390
+ path: str = ".",
391
+ recursive: bool = True,
392
+ exit_zero: bool = False,
393
+ *,
394
+ _wrappers: Optional[list[DeprecationWrapperInfo]] = None,
395
+ ) -> int:
396
+ """Scan Python code for misconfigured ``@deprecated`` wrappers and deprecation chains.
397
+
398
+ Reports invalid argument mappings (exit 1), identity mappings, no-effect wrappers,
399
+ deprecation chains, and ``args_mapping`` entries targeting POSITIONAL_ONLY constructor
400
+ parameters (all advisory warnings only, exit 0). Use the ``chains`` subcommand for a
401
+ dedicated hard-error chain check.
402
+
403
+ Args:
404
+ path: Path to the module, package directory, or importable module name to scan.
405
+ recursive: Scan submodules recursively (default True). Pass ``--norecursive`` to scan top-level only.
406
+ exit_zero: Always exit 0 even if hard errors (invalid argument mappings) are found.
407
+ Useful for advisory CI steps that should report but never block.
408
+ _wrappers: Pre-scanned wrapper list. When provided, skips the scan step. Underscore
409
+ prefix hides this parameter from the Fire CLI (internal use by ``cmd_all`` only).
410
+
411
+ Returns:
412
+ 0 on success or advisory-only issues; 1 when hard errors are found and ``exit_zero`` is False.
413
+
414
+ """
415
+ if _wrappers is None:
416
+ _print_scan_header(path)
417
+ with _managed_sys_path(path):
418
+ _wrappers = _scan_path(path, recursive=recursive)
419
+
420
+ if not _wrappers:
421
+ _print("No deprecated callables found.")
422
+ return 0
423
+
424
+ if _Reporter.issues(_wrappers, error_on_chains=False):
425
+ _print("\nIssues were found in deprecated wrappers.")
426
+ else:
427
+ _print("\nAll deprecated wrappers look correct!")
428
+
429
+ has_invalid = any(r.invalid_args for r in _wrappers)
430
+ return 1 if not exit_zero and has_invalid else 0
431
+
432
+
433
+ def cmd_expiry(
434
+ path: str = ".",
435
+ version: Optional[str] = None,
436
+ recursive: bool = True,
437
+ exit_zero: bool = False,
438
+ *,
439
+ _wrappers: Optional[list[DeprecationWrapperInfo]] = None,
440
+ ) -> int:
441
+ """Check for deprecated wrappers that have passed their scheduled removal version.
442
+
443
+ Requires the ``packaging`` library: ``pip install 'pyDeprecate[audit]'``.
444
+ A missing ``packaging`` library is treated as advisory (returns 0 with a warning).
445
+
446
+ Args:
447
+ path: Path to the module, package directory, or importable module name to scan.
448
+ version: Current package version for comparison (e.g. ``"2.0.0"``). Auto-detected
449
+ from installed package metadata if not provided.
450
+ recursive: Scan submodules recursively (default True). Pass ``--norecursive`` to scan top-level only.
451
+ exit_zero: Always exit 0 even if expired wrappers are found.
452
+ Useful for advisory CI steps that should report but never block.
453
+ _wrappers: Pre-scanned wrapper list. When provided, skips the scan step and derives
454
+ expired wrappers via ``_check_expiry_for_callables``. Requires *version* to be
455
+ non-``None`` when set. Underscore prefix hides this parameter from the Fire CLI
456
+ (internal use by ``cmd_all`` only).
457
+
458
+ Returns:
459
+ 0 on success or when the ``packaging`` library is unavailable; 1 when expired
460
+ wrappers are found and ``exit_zero`` is False.
461
+
462
+ """
463
+ # Fire auto-converts numeric-looking strings (e.g. "1.0" → float); normalise to str.
464
+ if version is not None:
465
+ version = str(version)
466
+ if _wrappers is None:
467
+ # Standalone path: full scan + version auto-detect inside _do_expiry.
468
+ resolved_version = version if version is not None else _auto_detect_version(_safe_module_name(path), path=path)
469
+ if resolved_version is None and version is None:
470
+ _print(
471
+ "Could not resolve the current package version automatically and no --version was given; "
472
+ "the expiry check runs without a resolved version and its result may be unreliable. "
473
+ "Pass --version explicitly for a definitive check.",
474
+ stderr=True,
475
+ )
476
+ _print_scan_header(path, resolved_version, user_provided=version is not None)
477
+ with _managed_sys_path(path):
478
+ raw = _do_expiry(path, resolved_version, recursive)
479
+ if raw is None: # packaging unavailable — warning already printed to stderr
480
+ return 0
481
+ expired = raw
482
+ else:
483
+ # Pre-scanned path: derive expired list from wrappers directly.
484
+ if version is None:
485
+ _print("Cannot check expiry: version not resolved. Pass --version explicitly.", stderr=True)
486
+ return 0
487
+ try:
488
+ expired = _check_expiry_for_callables(_wrappers, version)
489
+ except ImportError:
490
+ _print(
491
+ "The 'expiry' subcommand requires the 'packaging' library.\n"
492
+ "Install it with: `pip install 'pyDeprecate[audit]'`",
493
+ stderr=True,
494
+ )
495
+ return 0
496
+ if not expired:
497
+ _print("No expired deprecated wrappers found.")
498
+ return 0
499
+ _Reporter.expiry(expired)
500
+ _print(f"\n{len(expired)} expired wrapper(s) found.")
501
+ return 0 if exit_zero else 1
502
+
503
+
504
+ def cmd_chains(
505
+ path: str = ".",
506
+ recursive: bool = True,
507
+ exit_zero: bool = False,
508
+ *,
509
+ _wrappers: Optional[list[DeprecationWrapperInfo]] = None,
510
+ ) -> int:
511
+ """Detect deprecated wrappers whose ``target`` is itself a deprecated callable (chains).
512
+
513
+ Two chain kinds are detected: ``target`` (forwarding chain to another deprecated
514
+ callable) and ``stacked`` (composed argument mappings that should be collapsed).
515
+
516
+ Args:
517
+ path: Path to the module, package directory, or importable module name to scan.
518
+ recursive: Scan submodules recursively (default True). Pass ``--norecursive`` to scan top-level only.
519
+ exit_zero: Always exit 0 even if chains are found.
520
+ Useful for advisory CI steps that should report but never block.
521
+ _wrappers: Pre-scanned wrapper list. When provided, skips the scan step and filters
522
+ for ``chain_type is not None`` internally. Underscore prefix hides this parameter
523
+ from the Fire CLI (internal use by ``cmd_all`` only).
524
+
525
+ Returns:
526
+ 0 when no chains are found or ``exit_zero`` is True; 1 when chains are found.
527
+
528
+ """
529
+ if _wrappers is None:
530
+ _print_scan_header(path)
531
+ with _managed_sys_path(path):
532
+ _wrappers = validate_deprecation_chains(_resolve_module_name(path), recursive=recursive)
533
+ chains = [r for r in _wrappers if r.chain_type is not None]
534
+ if not chains:
535
+ _print("No deprecation chains found.")
536
+ return 0
537
+ _Reporter.chains(chains, error=True)
538
+ _print(f"\n{len(chains)} deprecation chain(s) found.")
539
+ return 0 if exit_zero else 1
540
+
541
+
542
+ def cmd_all(
543
+ path: str = ".",
544
+ version: Optional[str] = None,
545
+ recursive: bool = True,
546
+ exit_zero: bool = False,
547
+ ) -> int:
548
+ """Run all three checks then append a deprecation table.
549
+
550
+ Performs a single scan pass and distributes the wrappers to ``cmd_check``,
551
+ ``cmd_expiry``, and ``cmd_chains`` so the filesystem is only traversed once.
552
+ After all three checks complete, ``cmd_status`` is always called to append a
553
+ compact markdown deprecation table to the output.
554
+ Version is auto-detected from installed package metadata when not provided.
555
+ A missing ``packaging`` library skips the expiry check with a warning and does not
556
+ count as a hard error.
557
+
558
+ Args:
559
+ path: Path to the module, package directory, or importable module name to scan.
560
+ version: Current package version for expiry comparison (e.g. ``"2.0.0"``).
561
+ Auto-detected from installed package metadata if not provided.
562
+ recursive: Scan submodules recursively (default True). Pass ``--norecursive`` to scan top-level only.
563
+ exit_zero: Always exit 0 even if issues are found.
564
+ Useful for advisory CI steps that should report but never block.
565
+
566
+ Returns:
567
+ 0 when all checks pass or ``exit_zero`` is True; 1 when any hard error is found.
568
+ The deprecation table is always appended regardless of pass/fail outcome.
569
+
570
+ """
571
+ if version is not None:
572
+ version = str(version)
573
+ version_path = path if Path(path).exists() else None
574
+ resolved_version = (
575
+ version if version is not None else _auto_detect_version(_safe_module_name(path), path=version_path)
576
+ )
577
+ _print_scan_header(path, resolved_version, user_provided=version is not None)
578
+ with _managed_sys_path(path):
579
+ wrappers = _scan_path(path, recursive=recursive)
580
+
581
+ # Sub-commands run with exit_zero=False so cmd_all sees their truthful exit codes;
582
+ # the user-facing --exit-zero is applied to the aggregate below.
583
+ check_code = cmd_check(path, recursive=recursive, exit_zero=False, _wrappers=wrappers)
584
+ expiry_code = cmd_expiry(path, version=resolved_version, recursive=recursive, exit_zero=False, _wrappers=wrappers)
585
+ chains_code = cmd_chains(path, recursive=recursive, exit_zero=False, _wrappers=wrappers)
586
+
587
+ # The status table is a display artifact appended after the three gates. Render it defensively:
588
+ # a table-rendering failure must never change the aggregate exit code the three checks produced.
589
+ try:
590
+ cmd_status(path, version=resolved_version, recursive=recursive, _wrappers=wrappers)
591
+ except Exception as exc:
592
+ _print(f"Could not render the deprecation table: {exc}", stderr=True)
593
+
594
+ has_errors = bool(check_code or expiry_code or chains_code)
595
+ return 0 if not has_errors or exit_zero else 1
596
+
597
+
598
+ def cmd_status(
599
+ path: str = ".",
600
+ version: Optional[str] = None,
601
+ recursive: bool = True,
602
+ style: str = "compact",
603
+ include_members: bool = True,
604
+ output: Optional[str] = None,
605
+ *,
606
+ _wrappers: Optional[list[DeprecationWrapperInfo]] = None,
607
+ ) -> int:
608
+ """Print a markdown deprecation status table to stdout.
609
+
610
+ Scans the target package for deprecated wrappers and renders their lifecycle
611
+ status as a Markdown table. Standalone — runs no checks, always exits 0.
612
+ When ``--output`` is given, the table is also written to that file.
613
+
614
+ Args:
615
+ path: Path to the module, package directory, or importable module name to scan.
616
+ version: Current package version for lifecycle status (e.g. ``"2.0.0"``).
617
+ Auto-detected from installed package metadata if not provided.
618
+ recursive: Scan submodules recursively (default True). Pass ``--norecursive`` to scan top-level only.
619
+ style: Table format — ``compact`` (default) or ``matrix``.
620
+ include_members: Include deprecated class members such as methods and constructors (default True).
621
+ output: Optional file path to write the markdown table. The table is always
622
+ printed to stdout regardless of this flag.
623
+
624
+ Returns:
625
+ Always 0 — status table generation is not a pass/fail gate.
626
+
627
+ """
628
+ if version is not None:
629
+ version = str(version)
630
+ try:
631
+ table_style = TableStyle(style)
632
+ except ValueError:
633
+ valid = ", ".join(s.value for s in TableStyle)
634
+ _print(f"Invalid style {style!r}; falling back to 'compact'. Expected one of: {valid}.", stderr=True)
635
+ table_style = TableStyle.COMPACT
636
+
637
+ # Never resolve the importable module name eagerly: status "always exits 0" (it is not a
638
+ # pass/fail gate), so a plain directory without ``__init__.py`` — which ``check`` scans fine and
639
+ # for which ``_wrappers`` is already supplied by ``cmd_all`` — must not raise here. ``_safe_module_name``
640
+ # falls back to the raw path, used only as table metadata for version resolution.
641
+ module_name = _safe_module_name(path)
642
+ resolved_version = version if version is not None else _auto_detect_version(module_name, path=path)
643
+ if _wrappers is None:
644
+ _print_scan_header(path, resolved_version, user_provided=version is not None)
645
+ with _managed_sys_path(path):
646
+ _wrappers = _scan_path(path, recursive=recursive, include_members=include_members)
647
+ markdown = generate_deprecation_table(
648
+ module_name,
649
+ current_version=resolved_version,
650
+ style=table_style,
651
+ _wrappers=_wrappers,
652
+ )
653
+
654
+ if _Reporter._HAS_RICH:
655
+ from rich.markdown import Markdown
656
+
657
+ _Reporter._console().print(Markdown(markdown))
658
+ else:
659
+ _print(markdown)
660
+
661
+ if output is not None:
662
+ out_path = Path(output)
663
+ out_path.parent.mkdir(parents=True, exist_ok=True)
664
+ out_path.write_text(markdown, encoding="utf-8")
665
+ _print(f"→ Saved to: {out_path}", stderr=True)
666
+
667
+ return 0
668
+
669
+
670
+ # ---------------------------------------------------------------------------
671
+ # CLI entry point
672
+ # ---------------------------------------------------------------------------
673
+
674
+
675
+ def _ensure_utf8_streams() -> None:
676
+ """Reconfigure stdout/stderr to UTF-8 on platforms where the default encoding may reject non-ASCII characters.
677
+
678
+ On Windows the default console codec (``charmap``) cannot encode Unicode emoji used by
679
+ :class:`~deprecate.audit.DeprecationStatus`. Calling ``reconfigure`` before any output is written ensures emoji
680
+ reach the terminal (or CI log) without a :exc:`UnicodeEncodeError`.
681
+
682
+ The call is a no-op when the streams are already UTF-8 or when they lack a ``reconfigure`` method (binary streams,
683
+ pytest capture wrappers).
684
+
685
+ """
686
+ for stream in (sys.stdout, sys.stderr):
687
+ # ``encoding`` may be *present but None* (e.g. some redirected/binary-ish wrappers); ``getattr`` with a
688
+ # default only covers a missing attribute, so guard the ``None`` case with ``or "utf-8"`` before ``.lower()``.
689
+ encoding = (getattr(stream, "encoding", None) or "utf-8").lower()
690
+ if hasattr(stream, "reconfigure") and encoding != "utf-8":
691
+ with contextlib.suppress(Exception):
692
+ stream.reconfigure(encoding="utf-8")
693
+
694
+
695
+ def cli() -> None:
696
+ """CLI entry point for pydeprecate.
697
+
698
+ The subcommand's integer return value becomes the process exit code, applied *after* ``fire.Fire``
699
+ returns. Raising ``SystemExit`` from inside the Fire trace would abort Fire's own unconsumed-argument
700
+ check, silently ignoring unknown or misspelled flags (exit 0 on typos); letting the trace complete
701
+ makes Fire report ``Could not consume arg`` and exit 2 for such flags. Acts as the single top-level
702
+ exception handler: unhandled exceptions from subcommands are converted to a non-zero exit with the
703
+ exception type and message (the type prefix guarantees a non-blank stderr line even when the exception
704
+ carries no message). SystemExit (Fire's ``--help`` and error exits) passes through unchanged.
705
+
706
+ A path whose name collides with a subcommand (``check``, ``expiry``, ``chains``, ``all``, ``status``) is
707
+ treated as that subcommand by the implicit-``check`` shim. Scan such a path explicitly, e.g.
708
+ ``pydeprecate check ./check``, so the leading token is the subcommand and the path is its argument.
709
+
710
+ """
711
+ _ensure_utf8_streams()
712
+ try:
713
+ import fire
714
+ except ImportError:
715
+ sys.exit("The 'pydeprecate' CLI requires the 'fire' package.\nInstall it with: pip install 'pyDeprecate[cli]'")
716
+
717
+ subcommands = {"check", "expiry", "chains", "all", "status"}
718
+ argv = sys.argv[1:]
719
+ if argv and argv[0] not in subcommands and argv[0] not in {"-h", "--help"}:
720
+ argv = ["check", *argv]
721
+
722
+ exit_code: Optional[int] = None
723
+
724
+ def _capture(fn: Callable[..., int]) -> Callable[..., None]:
725
+ """Record the cmd_* return code without returning it into the Fire trace.
726
+
727
+ Returning the int would make Fire print it and treat it as a further component to consume arguments against;
728
+ returning ``None`` keeps the output clean and lets Fire finish its trace.
729
+
730
+ """
731
+
732
+ @functools.wraps(fn)
733
+ def wrapper(*args: object, **kwargs: object) -> None:
734
+ nonlocal exit_code
735
+ exit_code = fn(*args, **kwargs)
736
+
737
+ return wrapper
738
+
739
+ try:
740
+ fire.Fire(
741
+ {
742
+ "check": _capture(cmd_check),
743
+ "expiry": _capture(cmd_expiry),
744
+ "chains": _capture(cmd_chains),
745
+ "all": _capture(cmd_all),
746
+ "status": _capture(cmd_status),
747
+ },
748
+ command=argv,
749
+ )
750
+ except Exception as exc: # SystemExit is BaseException — Fire's own exits pass through untouched
751
+ # Prefix the exception type so an exception with an empty message still produces a non-blank stderr
752
+ # line (bare ``str(exc)`` on such exceptions exited 1 with nothing printed).
753
+ sys.exit(f"{type(exc).__name__}: {exc}")
754
+ # exit_code stays None when no subcommand ran (bare `pydeprecate` help) → return normally (exit 0).
755
+ if exit_code is not None:
756
+ sys.exit(exit_code)
.venv/lib/python3.12/site-packages/deprecate/_pkg.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Package and filesystem helpers for pyDeprecate's CLI.
2
+
3
+ Internal utilities that resolve a package's version, locate package directories, and manage ``sys.path`` for scanning.
4
+
5
+ Version resolution uses a local ``pyproject.toml`` (development checkout) when available, falling back to installed
6
+ distribution metadata via ``importlib.metadata``.
7
+
8
+ TOML parsing uses ``tomllib`` (stdlib on Python 3.11+) or ``tomli`` (backport, via ``pip install 'pyDeprecate[audit]'``
9
+ on Python 3.9-3.10). When not available the helpers return ``None`` and callers fall back to ``importlib.metadata``.
10
+
11
+ This module is private (no ``__all__``); its surface may change without notice.
12
+
13
+ """
14
+
15
+ import importlib
16
+ import importlib.metadata
17
+ import os
18
+ import sys
19
+ import warnings
20
+ from collections.abc import Generator
21
+ from contextlib import contextmanager, suppress
22
+ from pathlib import Path
23
+ from typing import Any, Optional
24
+
25
+
26
+ def _load_toml(path: str) -> dict[str, Any]:
27
+ r"""Load a TOML file using ``tomllib`` (Python 3.11+) or ``tomli`` (Python 3.10 backport).
28
+
29
+ Returns an empty dict on any failure (missing library, parse error, IO).
30
+
31
+ Examples:
32
+ >>> import os, tempfile
33
+ >>> with tempfile.NamedTemporaryFile(suffix=".toml", mode="w", delete=False) as f:
34
+ ... _ = f.write('[project]\nname = "mypkg"\nversion = "1.2.3"\n')
35
+ ... name = f.name
36
+ >>> _load_toml(name).get("project", {}).get("version")
37
+ '1.2.3'
38
+ >>> os.unlink(name)
39
+
40
+ """
41
+ try:
42
+ try:
43
+ import tomllib
44
+ except ImportError:
45
+ import tomli as tomllib # Python 3.10 backport
46
+
47
+ with open(path, "rb") as fh:
48
+ return dict(tomllib.load(fh))
49
+ except Exception:
50
+ return {}
51
+
52
+
53
+ def _version_from_dynamic(pkg_name: str, scan_path: str, pyproject_dir: str) -> Optional[str]:
54
+ """Import *pkg_name* and return its ``__version__``, or ``None`` on any failure.
55
+
56
+ Adds candidate import roots (scan dir, its parent, pyproject dir, ``src/``
57
+ sub-dir) to ``sys.path`` before importing, then restores the original
58
+ ``sys.path`` unconditionally via ``finally``.
59
+
60
+ Args:
61
+ pkg_name: Importable package name declared in ``[project].name``.
62
+ scan_path: File-system path originally passed to the CLI (used to
63
+ locate the package root).
64
+ pyproject_dir: Directory containing the ``pyproject.toml`` file.
65
+
66
+ Returns:
67
+ Version string from ``pkg.__version__`` or ``None``.
68
+
69
+ """
70
+ scan_root = os.path.abspath(scan_path) if os.path.isdir(scan_path) else os.path.dirname(os.path.abspath(scan_path))
71
+ original = list(sys.path)
72
+ added: list[str] = []
73
+ for root in (scan_root, os.path.dirname(scan_root), pyproject_dir, os.path.join(pyproject_dir, "src")):
74
+ if root and os.path.isdir(root) and root not in added:
75
+ added.append(root)
76
+ sys.path.insert(0, root)
77
+ try:
78
+ module = importlib.import_module(pkg_name)
79
+ version = getattr(module, "__version__", None)
80
+ return version if isinstance(version, str) else None
81
+ except Exception:
82
+ return None
83
+ finally:
84
+ sys.path[:] = original
85
+
86
+
87
+ def _version_from_toml(toml_path: str, scan_path: str) -> Optional[str]:
88
+ """Extract ``[project].version`` from *toml_path*, or ``None``.
89
+
90
+ Falls back to importing the package for ``dynamic = ["version"]`` projects.
91
+
92
+ Args:
93
+ toml_path: Absolute path to a ``pyproject.toml`` file.
94
+ scan_path: Original file-system path passed to the CLI (forwarded to
95
+ :func:`_version_from_dynamic` for import-root resolution).
96
+
97
+ Returns:
98
+ Version string or ``None`` when not resolvable.
99
+
100
+ """
101
+ data = _load_toml(toml_path)
102
+ project = data.get("project", {})
103
+ if not project:
104
+ return None
105
+
106
+ version = project.get("version")
107
+ if isinstance(version, str):
108
+ return version
109
+
110
+ if "version" in project.get("dynamic", []):
111
+ pkg_name = project.get("name")
112
+ if isinstance(pkg_name, str) and pkg_name:
113
+ return _version_from_dynamic(pkg_name, scan_path, os.path.dirname(toml_path))
114
+
115
+ return None
116
+
117
+
118
+ def _read_pyproject_version(path: str) -> Optional[str]:
119
+ """Return ``[project].version`` from the nearest ``pyproject.toml`` up to 2 levels above *path*.
120
+
121
+ Searches the directory itself, its parent, and its grandparent — stops
122
+ as soon as a resolvable version is found or the limit is reached.
123
+
124
+ Args:
125
+ path: File-system path to start the upward search from.
126
+
127
+ Returns:
128
+ Version string or ``None`` when not found within 2 levels.
129
+
130
+ """
131
+ candidate = os.path.abspath(path)
132
+ if not os.path.isdir(candidate):
133
+ candidate = os.path.dirname(candidate)
134
+ for _ in range(3): # current dir + 2 levels up
135
+ toml_path = os.path.join(candidate, "pyproject.toml")
136
+ if os.path.isfile(toml_path):
137
+ version = _version_from_toml(toml_path, path)
138
+ if version is not None:
139
+ return version
140
+ parent = os.path.dirname(candidate)
141
+ if parent == candidate:
142
+ break
143
+ candidate = parent
144
+ return None
145
+
146
+
147
+ def _auto_detect_version(module_name: str, path: Optional[str] = None) -> Optional[str]:
148
+ """Return the version for *module_name*, or ``None`` on any failure.
149
+
150
+ Priority order:
151
+
152
+ 1. ``[project].version`` in the nearest ``pyproject.toml`` above *path* (reflects
153
+ local development checkouts whose version may differ from the installed dist).
154
+ 2. ``importlib.metadata.version(module_name)`` — the installed distribution.
155
+
156
+ Args:
157
+ module_name: Importable package name whose installed version to look up.
158
+ path: Optional file-system path used to locate a local ``pyproject.toml``.
159
+ Only consulted when it actually exists on the filesystem; an importable
160
+ module *name* passed through here is ignored, because the walk-up from the
161
+ current working directory would otherwise pick up an unrelated project's
162
+ ``pyproject.toml`` version. When honored, the local file takes precedence
163
+ over installed metadata.
164
+
165
+ Returns:
166
+ Version string (e.g. ``"1.2.3"``) or ``None`` when the package is not
167
+ installed or the version cannot be determined.
168
+
169
+ """
170
+ # Guard: a bare module name (not an existing path) must not trigger the pyproject.toml
171
+ # walk-up — starting from cwd it would grab whatever unrelated project the caller is
172
+ # standing in, flipping expiry gates on a foreign version.
173
+ if path is not None and os.path.exists(path):
174
+ local_ver = _read_pyproject_version(path)
175
+ if local_ver is not None:
176
+ return local_ver
177
+ with suppress(Exception):
178
+ return importlib.metadata.version(module_name)
179
+ # The import name (deprecate, PIL, sklearn) often differs from the distribution name
180
+ # (pyDeprecate, Pillow, scikit-learn) that importlib.metadata.version() requires. Map the
181
+ # import package to its distribution and retry before giving up.
182
+ dist_name = _distribution_for_import(module_name)
183
+ if dist_name is not None:
184
+ try:
185
+ return importlib.metadata.version(dist_name)
186
+ except Exception:
187
+ return None
188
+ return None
189
+
190
+
191
+ def _distribution_for_import(import_name: str) -> Optional[str]:
192
+ """Map a top-level import package name to its installed distribution name.
193
+
194
+ ``importlib.metadata.version`` needs the *distribution* name (``pyDeprecate``) while the CLI is
195
+ handed the *import* name (``deprecate``). Uses ``importlib.metadata.packages_distributions`` on
196
+ Python 3.11+ and falls back to scanning each distribution's ``top_level.txt`` on Python <3.11.
197
+
198
+ Args:
199
+ import_name: Importable (possibly dotted) package name; only the first component is used.
200
+
201
+ Returns:
202
+ The first distribution name that provides the top-level package, or ``None`` when no
203
+ installed distribution exposes it.
204
+
205
+ """
206
+ top_level = import_name.split(".")[0]
207
+ packages_distributions = getattr(importlib.metadata, "packages_distributions", None)
208
+ if callable(packages_distributions):
209
+ try:
210
+ distributions = packages_distributions().get(top_level)
211
+ except Exception:
212
+ return None
213
+ return distributions[0] if distributions else None
214
+ # Python <3.11: packages_distributions is unavailable — read top_level.txt from each distribution.
215
+ return _distribution_from_top_level(top_level)
216
+
217
+
218
+ def _distribution_from_top_level(top_level: str) -> Optional[str]:
219
+ """Return the distribution whose ``top_level.txt`` lists *top_level* (Python <3.11 fallback)."""
220
+ try:
221
+ distributions = list(importlib.metadata.distributions())
222
+ except Exception:
223
+ return None
224
+ for dist in distributions:
225
+ try:
226
+ listed = dist.read_text("top_level.txt")
227
+ except Exception:
228
+ listed = None
229
+ if listed and top_level in listed.split():
230
+ try:
231
+ name = dist.metadata["Name"]
232
+ except KeyError:
233
+ continue
234
+ if name:
235
+ return name
236
+ return None
237
+
238
+
239
+ def _is_package_dir(pth: Path) -> bool:
240
+ """Return True if *pth* is an importable package directory (contains ``__init__.py``)."""
241
+ return (pth / "__init__.py").exists()
242
+
243
+
244
+ def _find_child_packages(pth: Path) -> list[Path]:
245
+ """Return package sub-directories of *pth*, checking ``src/`` when none found directly.
246
+
247
+ Resolution order:
248
+ 1. Immediate child directories of ``pth/src/`` that contain ``__init__.py``
249
+ (standard ``src/``-layout projects take precedence).
250
+ 2. If none, immediate child directories of *pth* that contain ``__init__.py``.
251
+
252
+ Args:
253
+ pth: Directory to search.
254
+
255
+ Returns:
256
+ List of :class:`~pathlib.Path` objects for each package directory found.
257
+
258
+ """
259
+ src_dir = pth / "src"
260
+ if src_dir.is_dir():
261
+ in_src = [c for c in src_dir.iterdir() if c.is_dir() and _is_package_dir(c)]
262
+ if in_src:
263
+ return in_src
264
+ return [c for c in pth.iterdir() if c.is_dir() and _is_package_dir(c)]
265
+
266
+
267
+ @contextmanager
268
+ def _managed_sys_path(path: str) -> Generator[None, None, None]:
269
+ """Context manager that prepends the import root to ``sys.path`` and restores it after scanning.
270
+
271
+ For package directories (containing ``__init__.py``), inserts the parent directory so the package name resolves as
272
+ an importable module. For plain directories, inserts the directory itself. Importable module name strings are passed
273
+ through unchanged.
274
+
275
+ Warning:
276
+ Not thread-safe. ``sys.path`` is a process-global list; concurrent use from multiple threads will corrupt
277
+ the restored state. Each scan should run in a dedicated process or be serialized via a lock.
278
+
279
+ """
280
+ abs_path: Path = Path(path).resolve()
281
+ original = list(sys.path)
282
+ if abs_path.is_dir():
283
+ if _is_package_dir(abs_path):
284
+ import_root = str(abs_path.parent)
285
+ else:
286
+ src_dir = abs_path / "src"
287
+ in_src = src_dir.is_dir() and any(c.is_dir() and _is_package_dir(c) for c in src_dir.iterdir())
288
+ import_root = str(src_dir) if in_src else str(abs_path)
289
+ sys.path.insert(0, import_root)
290
+ try:
291
+ with warnings.catch_warnings():
292
+ warnings.filterwarnings("ignore", category=DeprecationWarning, module="deprecate.*")
293
+ warnings.filterwarnings("ignore", category=FutureWarning, module="deprecate.*")
294
+ yield
295
+ finally:
296
+ sys.path[:] = original
297
+
298
+
299
+ def _resolve_module_name(path: str) -> str:
300
+ """Convert a filesystem path to an importable module name.
301
+
302
+ Accepts a package directory (with ``__init__.py``) or an importable module
303
+ name string. Plain directories and individual ``.py`` files are not supported
304
+ because ``validate_deprecation_expiry`` and ``validate_deprecation_chains``
305
+ require an importable module name, not a filesystem path.
306
+
307
+ Args:
308
+ path: Package directory path or importable module name string.
309
+
310
+ Returns:
311
+ Importable module name string.
312
+
313
+ Raises:
314
+ ValueError: If path is a plain directory without ``__init__.py``, a ``.py``
315
+ file, or cannot be resolved to an importable module name.
316
+
317
+ """
318
+ pth = Path(path)
319
+ if pth.is_file():
320
+ raise ValueError(
321
+ f"File paths are not supported: {path!r}. Pass an importable module/package name or a directory instead."
322
+ )
323
+ if pth.is_dir():
324
+ if _is_package_dir(pth):
325
+ return pth.resolve().name
326
+ # Flat src-layout or project root: find package in direct children or src/ subdir.
327
+ child_pkgs = _find_child_packages(pth)
328
+ if len(child_pkgs) == 1:
329
+ return child_pkgs[0].name
330
+ if len(child_pkgs) > 1:
331
+ names = ", ".join(sorted(c.name for c in child_pkgs))
332
+ raise ValueError(
333
+ f"Directory {path!r} contains multiple packages ({names}). "
334
+ "Pass the specific package sub-directory instead."
335
+ )
336
+ raise ValueError(
337
+ f"Plain directories without '__init__.py' are not supported for expiry or chain checks: {path!r}. "
338
+ "Use an importable package layout with '__init__.py', or pass an importable module name instead."
339
+ )
340
+ return path
341
+
342
+
343
+ def _safe_module_name(path: str) -> str:
344
+ """Return the importable module name for *path*, falling back to *path* itself."""
345
+ try:
346
+ return _resolve_module_name(path)
347
+ except ValueError:
348
+ return path
.venv/lib/python3.12/site-packages/deprecate/_types.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared type definitions for pyDeprecate.
2
+
3
+ This module provides typed interfaces consumed by the decorator, proxy, and audit modules so that static analysers can
4
+ catch schema mismatches at analysis time rather than silently returning ``None`` at runtime.
5
+
6
+ """
7
+
8
+ import copy
9
+ import threading
10
+ import warnings
11
+ from collections.abc import Mapping
12
+ from dataclasses import dataclass, field, replace
13
+ from enum import Enum
14
+ from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Protocol, Union, runtime_checkable
15
+
16
+ if TYPE_CHECKING:
17
+ from typing_extensions import TypeGuard
18
+
19
+
20
+ class TargetMode(Enum):
21
+ """Selects ``@deprecated`` behaviour when no callable replacement is provided.
22
+
23
+ Attributes:
24
+ NOTIFY: Notify-only deprecation -- warn on every call; original body executes unchanged. Replaces
25
+ ``target=None``. Passing ``args_mapping`` or ``args_extra`` with this mode emits a :class:`UserWarning`
26
+ today; :class:`TypeError` is planned in ``v1.0``.
27
+ ARGS_REMAP: Deprecate argument names only -- warn only when deprecated argument names are passed; remaps
28
+ kwargs via ``args_mapping`` before calling the original body. Replaces ``target=True``. This mode is
29
+ strongly recommended with ``args_mapping``; omitting it emits a :class:`UserWarning` today, and
30
+ :class:`TypeError` is planned in ``v1.0``.
31
+ ATTRS_REMAP: Selective per-attribute deprecation -- warn only when a deprecated attribute alias listed in
32
+ ``attrs_mapping`` is accessed; all other attribute access is forwarded silently. Proxy-specific mode:
33
+ only valid for :func:`~deprecate.proxy.deprecated_class`; raises :class:`TypeError` on
34
+ :func:`~deprecate.deprecated` decorated functions/methods. Analogous to :attr:`ARGS_REMAP` but for
35
+ attribute access instead of call arguments. This mode is selected automatically when ``attrs_mapping``
36
+ is non-empty and no explicit ``target`` is provided.
37
+
38
+ Examples:
39
+ >>> from deprecate import TargetMode
40
+ >>> TargetMode.NOTIFY.value
41
+ 'notify'
42
+ >>> TargetMode.ARGS_REMAP.value
43
+ 'args_remap'
44
+ >>> TargetMode.ATTRS_REMAP.value
45
+ 'attrs_remap'
46
+
47
+ """
48
+
49
+ NOTIFY = "notify"
50
+ ARGS_REMAP = "args_remap"
51
+ ATTRS_REMAP = "attrs_remap"
52
+
53
+ @classmethod
54
+ def _from_legacy(
55
+ cls,
56
+ target: Union[None, bool],
57
+ *,
58
+ stacklevel: Optional[int] = 3,
59
+ ) -> "TargetMode":
60
+ """Convert ``target`` sentinel (``None`` / ``True`` / ``False``) to :class:`~deprecate._types.TargetMode`.
61
+
62
+ Backwards-compatibility shim for the :func:`~deprecate.deprecated` decorator. Each sentinel is mapped to its
63
+ modern equivalent and a deprecation warning is emitted. Pass ``stacklevel=None`` to suppress all warnings.
64
+
65
+ Args:
66
+ target: Legacy sentinel — ``None`` → :attr:`~deprecate._types.TargetMode.NOTIFY`,
67
+ ``True`` → :attr:`~deprecate._types.TargetMode.ARGS_REMAP`,
68
+ ``False`` → :attr:`~deprecate._types.TargetMode.NOTIFY` (not a valid mode; :class:`TypeError` in v1.0).
69
+ stacklevel: Stack level forwarded to :func:`warnings.warn`. Pass ``None`` to suppress all warnings
70
+ entirely. Defaults to ``3``.
71
+
72
+ Returns:
73
+ The corresponding :class:`~deprecate._types.TargetMode` member.
74
+
75
+ Raises:
76
+ TypeError: If ``target`` is anything other than ``None``, ``True``, or ``False``.
77
+
78
+ Examples:
79
+ >>> TargetMode._from_legacy(None, stacklevel=None)
80
+ <TargetMode.NOTIFY: 'notify'>
81
+ >>> TargetMode._from_legacy(True, stacklevel=None)
82
+ <TargetMode.ARGS_REMAP: 'args_remap'>
83
+ >>> TargetMode._from_legacy(False, stacklevel=None)
84
+ <TargetMode.NOTIFY: 'notify'>
85
+
86
+ """
87
+ if target is None:
88
+ if stacklevel is not None:
89
+ warnings.warn(
90
+ "target=None is deprecated since `v0.8`; use `TargetMode.NOTIFY` instead."
91
+ " Will be removed in `v1.0`.",
92
+ FutureWarning,
93
+ stacklevel=stacklevel,
94
+ )
95
+ return cls.NOTIFY
96
+ if target is True:
97
+ if stacklevel is not None:
98
+ warnings.warn(
99
+ "target=True is deprecated since `v0.8`; use `TargetMode.ARGS_REMAP` instead."
100
+ " Will be removed in `v1.0`.",
101
+ FutureWarning,
102
+ stacklevel=stacklevel,
103
+ )
104
+ return cls.ARGS_REMAP
105
+ if target is False:
106
+ if stacklevel is not None:
107
+ warnings.warn(
108
+ "`target=False` is not a valid deprecation mode and will be treated as `TargetMode.NOTIFY`."
109
+ " This will be `TypeError` in `v1.0`.",
110
+ UserWarning,
111
+ stacklevel=stacklevel,
112
+ )
113
+ return cls.NOTIFY
114
+ raise TypeError(
115
+ f"`TargetMode._from_legacy` accepts only None, True, or False; got {type(target).__name__}: {target!r}."
116
+ )
117
+
118
+ @classmethod
119
+ def _from_legacy_proxy(
120
+ cls,
121
+ target: Any, # noqa: ANN401
122
+ *,
123
+ args_mapping: Optional[Mapping[str, Optional[str]]] = None,
124
+ stacklevel: Optional[int] = 3,
125
+ ) -> "Union[Callable[..., Any], TargetMode, None]":
126
+ """Normalise a proxy-specific legacy ``target`` sentinel for :func:`~deprecate.proxy.deprecated_class`.
127
+
128
+ ``True`` and ``False`` are invalid for the proxy context and normalise to
129
+ :attr:`~deprecate._types.TargetMode.NOTIFY`
130
+ (or :attr:`~deprecate._types.TargetMode.ARGS_REMAP` when ``args_mapping`` is non-empty)
131
+ after emitting a warning.
132
+ All other values pass through unchanged. Pass ``stacklevel=None`` to suppress warnings.
133
+
134
+ Args:
135
+ target: Raw ``target`` value from the caller. Only ``True`` and ``False`` trigger normalisation;
136
+ any other value is returned as-is.
137
+ args_mapping: The ``args_mapping`` dict supplied to :func:`~deprecate.deprecated_class`, or ``None`` when
138
+ not provided. When ``target=True`` and ``args_mapping`` is non-empty the result is
139
+ :attr:`~deprecate._types.TargetMode.ARGS_REMAP` instead of
140
+ :attr:`~deprecate._types.TargetMode.NOTIFY`, and a :class:`FutureWarning` is emitted.
141
+ stacklevel: Stack level forwarded to :func:`warnings.warn`. Pass ``None`` to suppress all warnings.
142
+ Defaults to ``3``.
143
+
144
+ Returns:
145
+ :attr:`~deprecate._types.TargetMode.ARGS_REMAP` when ``target=True`` and ``args_mapping`` is non-empty;
146
+ :attr:`~deprecate._types.TargetMode.NOTIFY` when ``target`` was ``True`` (without ``args_mapping``) or
147
+ ``False``; otherwise ``target`` unchanged.
148
+
149
+ Examples:
150
+ >>> TargetMode._from_legacy_proxy(True, stacklevel=None)
151
+ <TargetMode.NOTIFY: 'notify'>
152
+ >>> TargetMode._from_legacy_proxy(True, args_mapping={"old": "new"}, stacklevel=None)
153
+ <TargetMode.ARGS_REMAP: 'args_remap'>
154
+ >>> TargetMode._from_legacy_proxy(False, stacklevel=None)
155
+ <TargetMode.NOTIFY: 'notify'>
156
+ >>> TargetMode._from_legacy_proxy(None) is None
157
+ True
158
+ >>> TargetMode._from_legacy_proxy(TargetMode.NOTIFY)
159
+ <TargetMode.NOTIFY: 'notify'>
160
+
161
+ """
162
+ if target is True:
163
+ if args_mapping:
164
+ if stacklevel is not None:
165
+ warnings.warn(
166
+ "`target=True` with `args_mapping` will resolve to `TargetMode.ARGS_REMAP`."
167
+ " Will be `TypeError` in `v1.0`.",
168
+ FutureWarning,
169
+ stacklevel=stacklevel,
170
+ )
171
+ return cls.ARGS_REMAP
172
+ if stacklevel is not None:
173
+ warnings.warn(
174
+ "`target=True` without `args_mapping` resolves to `TargetMode.NOTIFY`"
175
+ " (warns on every access). Will be `TypeError` in `v1.0`.",
176
+ FutureWarning,
177
+ stacklevel=stacklevel,
178
+ )
179
+ return cls.NOTIFY
180
+ if target is False:
181
+ if stacklevel is not None:
182
+ warnings.warn(
183
+ "`target=False` is not valid for `deprecated_class()`. Will be `TypeError` in `v1.0`.",
184
+ UserWarning,
185
+ stacklevel=stacklevel,
186
+ )
187
+ return cls.NOTIFY
188
+ return target
189
+
190
+ @classmethod
191
+ def _validate(
192
+ cls,
193
+ mode: "TargetMode",
194
+ source_name: str,
195
+ args_mapping: Optional[Mapping[str, Optional[str]]] = None,
196
+ args_extra: Optional[dict[str, Any]] = None,
197
+ *,
198
+ stacklevel: Optional[int] = 2,
199
+ ) -> bool:
200
+ """Validate :class:`~deprecate._types.TargetMode` against supplied configuration and emit misconfig warnings.
201
+
202
+ Checks three misconfiguration combinations and emits a :class:`UserWarning` for each one found.
203
+ These warnings will become :class:`TypeError` in ``v1.0``.
204
+
205
+ Misconfiguration warnings are always emitted via :func:`warnings.warn` with ``UserWarning`` — they are
206
+ construction-time guards independent of the runtime ``stream`` callable used for deprecation notices.
207
+
208
+ Args:
209
+ mode: The resolved :class:`~deprecate._types.TargetMode` to validate.
210
+ source_name: ``__name__`` of the decorated source callable, used in warning messages.
211
+ args_mapping: The ``args_mapping`` dict supplied to :func:`~deprecate.deprecated`, or ``None`` when not
212
+ provided.
213
+ args_extra: The ``args_extra`` dict supplied to :func:`~deprecate.deprecated`, or ``None`` when not
214
+ provided.
215
+ stacklevel: Stack level forwarded to :func:`warnings.warn` so that reported locations point at the
216
+ decorator application site. Pass ``None`` to suppress all warnings. Defaults to ``2``.
217
+
218
+ Returns:
219
+ ``True`` if any misconfiguration was detected, ``False`` if the configuration is valid.
220
+
221
+ Examples:
222
+ >>> TargetMode._validate(TargetMode.ARGS_REMAP, "my_func", args_mapping=None, stacklevel=None)
223
+ True
224
+ >>> TargetMode._validate(TargetMode.NOTIFY, "my_func", args_mapping={"old": "new"}, stacklevel=None)
225
+ True
226
+ >>> TargetMode._validate(TargetMode.NOTIFY, "my_func", args_extra={"bias": 1}, stacklevel=None)
227
+ True
228
+ >>> TargetMode._validate(TargetMode.NOTIFY, "my_func", stacklevel=None)
229
+ False
230
+
231
+ """
232
+ messages = []
233
+ if mode is cls.ARGS_REMAP and not args_mapping:
234
+ messages.append(
235
+ f"`@deprecated(target=TargetMode.ARGS_REMAP)` on `{source_name}` requires "
236
+ "`args_mapping` to specify which arguments are being renamed. Without it the "
237
+ "decorator has zero effect. This will be `TypeError` in `v1.0`."
238
+ )
239
+ if mode is cls.NOTIFY and args_mapping:
240
+ messages.append(
241
+ f"`@deprecated(target=TargetMode.NOTIFY)` on `{source_name}` ignores "
242
+ "`args_mapping`. Use `TargetMode.ARGS_REMAP` to rename arguments, or pass a "
243
+ "callable target to forward the call. This will be `TypeError` in `v1.0`."
244
+ )
245
+ if mode is cls.NOTIFY and args_extra:
246
+ messages.append(
247
+ f"`@deprecated(target=TargetMode.NOTIFY)` on `{source_name}` ignores "
248
+ "`args_extra`. Use a callable target to forward with extra arguments. "
249
+ "This will be `TypeError` in `v1.0`."
250
+ )
251
+ if stacklevel is not None:
252
+ for msg in messages:
253
+ warnings.warn(msg, UserWarning, stacklevel=stacklevel)
254
+ return bool(messages)
255
+
256
+ @classmethod
257
+ def _validate_proxy(
258
+ cls,
259
+ mode: "Union[TargetMode, Callable[..., Any], None]",
260
+ source_name: str,
261
+ attrs_mapping: Optional[Mapping[str, Optional[str]]] = None,
262
+ args_mapping: Optional[Mapping[str, Optional[str]]] = None,
263
+ args_extra: Optional[dict[str, Any]] = None,
264
+ *,
265
+ stacklevel: Optional[int] = 2,
266
+ ) -> bool:
267
+ """Validate proxy-specific configuration: ``attrs_mapping`` combinations.
268
+
269
+ Catches misconfiguration pairs involving ``attrs_mapping`` that the existing
270
+ :meth:`~deprecate._types.TargetMode._validate` does not cover (it handles only ``args_mapping`` /
271
+ ``args_extra`` and is used by the function-decorator path as well).
272
+
273
+ Misconfiguration warnings will become :class:`TypeError` in ``v1.0``.
274
+
275
+ Args:
276
+ mode: Resolved target (:class:`~deprecate._types.TargetMode` member, callable, or ``None``).
277
+ source_name: ``__name__`` of the decorated class, for warning messages.
278
+ attrs_mapping: The ``attrs_mapping`` dict passed to :func:`~deprecate.proxy.deprecated_class`, or
279
+ ``None``.
280
+ args_mapping: The ``args_mapping`` dict, forwarded here so we can detect the
281
+ ``ATTRS_REMAP + args_mapping`` combination.
282
+ args_extra: The ``args_extra`` dict, forwarded here so we can detect the
283
+ ``ATTRS_REMAP + args_extra`` combination — ``ATTRS_REMAP`` governs attribute access only and
284
+ does not honour call-time kwarg injection.
285
+ stacklevel: Forwarded to :func:`warnings.warn`. Pass ``None`` to suppress warnings. Defaults to ``2``.
286
+
287
+ Returns:
288
+ ``True`` if any misconfiguration was detected, ``False`` otherwise.
289
+
290
+ Examples:
291
+ >>> TargetMode._validate_proxy(TargetMode.NOTIFY, "Cls", attrs_mapping={"a": "b"}, stacklevel=None)
292
+ True
293
+ >>> TargetMode._validate_proxy(TargetMode.ATTRS_REMAP, "Cls", attrs_mapping=None, stacklevel=None)
294
+ True
295
+ >>> TargetMode._validate_proxy(TargetMode.ATTRS_REMAP, "Cls", attrs_mapping={}, stacklevel=None)
296
+ True
297
+ >>> TargetMode._validate_proxy(TargetMode.ATTRS_REMAP, "Cls", attrs_mapping={"a": "b"}, stacklevel=None)
298
+ False
299
+ >>> TargetMode._validate_proxy(
300
+ ... TargetMode.ARGS_REMAP, "Cls",
301
+ ... args_mapping={"old": "new"}, attrs_mapping={"a": "b"}, stacklevel=None,
302
+ ... )
303
+ True
304
+ >>> TargetMode._validate_proxy(
305
+ ... TargetMode.ATTRS_REMAP, "Cls",
306
+ ... args_mapping={"old": "new"}, attrs_mapping={"a": "b"}, stacklevel=None,
307
+ ... )
308
+ True
309
+ >>> TargetMode._validate_proxy(
310
+ ... TargetMode.ATTRS_REMAP, "Cls",
311
+ ... attrs_mapping={"a": "b"}, args_extra={"bias": 1}, stacklevel=None,
312
+ ... )
313
+ True
314
+
315
+ """
316
+ messages = []
317
+ if mode is cls.NOTIFY and attrs_mapping:
318
+ messages.append(
319
+ f"`deprecated_class(target=TargetMode.NOTIFY)` on `{source_name}` ignores "
320
+ "`attrs_mapping`. Drop one of them: `attrs_mapping` switches to selective per-attribute "
321
+ "warning, which contradicts NOTIFY's warn-on-every-access semantics. "
322
+ "This will be `TypeError` in `v1.0`."
323
+ )
324
+ if mode is cls.ARGS_REMAP and args_mapping and attrs_mapping:
325
+ messages.append(
326
+ f"`deprecated_class` on `{source_name}` has both `args_mapping` and `attrs_mapping` "
327
+ "configured with `target=TargetMode.ARGS_REMAP`. `ARGS_REMAP` governs call-time argument "
328
+ "renames only; `attrs_mapping` is inactive in this mode. "
329
+ "`DeprecationConfig.target` no longer reflects that `attrs_mapping` is also active. "
330
+ "Pass an explicit callable `target=<class>` to activate both mappings on the same proxy. "
331
+ "This will be `TypeError` in `v1.0`."
332
+ )
333
+ if mode is cls.ATTRS_REMAP and not attrs_mapping:
334
+ messages.append(
335
+ f"`deprecated_class(target=TargetMode.ATTRS_REMAP)` on `{source_name}` requires "
336
+ "`attrs_mapping` to specify which attribute names are deprecated. Without it the "
337
+ "proxy has zero selective effect. This will be `TypeError` in `v1.0`."
338
+ )
339
+ if mode is cls.ATTRS_REMAP and args_mapping:
340
+ messages.append(
341
+ f"`deprecated_class(target=TargetMode.ATTRS_REMAP)` on `{source_name}` ignores `args_mapping`. "
342
+ "`ATTRS_REMAP` only governs attribute access; argument renames on `__call__` are not applied. "
343
+ "Use `target=<class>` (with both mappings) or `TargetMode.ARGS_REMAP` (with `args_mapping` only). "
344
+ "This will be `TypeError` in `v1.0`."
345
+ )
346
+ if mode is cls.ATTRS_REMAP and args_extra:
347
+ messages.append(
348
+ f"`deprecated_class(target=TargetMode.ATTRS_REMAP)` on `{source_name}` ignores `args_extra`. "
349
+ "`ATTRS_REMAP` only governs attribute access; call-time kwarg injection is not applied. "
350
+ "Use `target=<class>` to forward calls with extra arguments. "
351
+ "This will be `TypeError` in `v1.0`."
352
+ )
353
+ if attrs_mapping is not None and len(attrs_mapping) == 0:
354
+ messages.append(
355
+ f"`deprecated_class` on `{source_name}` received `attrs_mapping={{}}` (empty dict). "
356
+ "An empty mapping has no effect — remove it or add deprecated attribute names. "
357
+ "This will be `TypeError` in `v1.0`."
358
+ )
359
+ if stacklevel is not None:
360
+ for msg in messages:
361
+ warnings.warn(msg, UserWarning, stacklevel=stacklevel)
362
+ return bool(messages)
363
+
364
+
365
+ @dataclass(frozen=True)
366
+ class DeprecationConfig:
367
+ """Static deprecation metadata attached to deprecated callables as ``__deprecated__``.
368
+
369
+ All fields are always set — both :func:`~deprecate.deprecated`-decorated functions and
370
+ :class:`~deprecate.proxy._DeprecatedProxy` objects use this unified schema.
371
+
372
+ Attributes:
373
+ deprecated_in: Version string when the callable was deprecated.
374
+ remove_in: Version string when the callable will be removed.
375
+ name: Display the name of the deprecated source (function or class name).
376
+ target: Normalised target — ``None`` (default), :attr:`~deprecate._types.TargetMode.NOTIFY`,
377
+ :attr:`~deprecate._types.TargetMode.ARGS_REMAP`, :attr:`~deprecate._types.TargetMode.ATTRS_REMAP`,
378
+ or a callable. Legacy sentinels (``True``/``False``) are normalised at decoration time and never
379
+ stored verbatim.
380
+ args_extra: Optional kwargs injected into forwarded calls; stored for audit visibility.
381
+ misconfigured: ``True`` when an invalid raw target sentinel (``False``) was passed at decoration time.
382
+ Audit tools surface this via
383
+ :attr:`~deprecate.audit.DeprecationWrapperInfo.misconfigured_target`.
384
+ docstring_style: Docstring notice output style when ``update_docstring=True``.
385
+ template_mgs: Optional custom warning-message template (``%``-style placeholders) that overrides the built-in
386
+ templates at warn time. ``None`` (default) keeps the built-in template selected for the active scenario.
387
+ Audit tools may surface this for introspection. See :func:`~deprecate.deprecation.deprecated` for the
388
+ available placeholders (e.g. ``%(source_name)s``, ``%(target_path)s``, ``%(deprecated_in)s``).
389
+ attrs_mapping: Optional mapping of deprecated attribute names to their canonical replacement names (or
390
+ ``None`` for warn-only). Set by :func:`~deprecate.proxy.deprecated_class` when
391
+ selective per-attribute deprecation is enabled. Non-``None`` redirect targets must be existing attribute
392
+ names on the target class when ``target`` is provided, or on the wrapped source class otherwise.
393
+ Non-cyclic chains are stored and surfaced by audit tooling. ``None`` (default) means the proxy uses its
394
+ blanket-warning behaviour (every attribute access emits a warning).
395
+ args_mapping: Optional dict remapping argument names; values are a plain string (new argument name) or
396
+ ``None`` (drop the argument).
397
+ args_mapping_auto_expanded: Keys that were automatically copied from ``attrs_mapping`` into
398
+ ``args_mapping`` by the dataclass dual-surface expansion in
399
+ :class:`~deprecate.proxy._DeprecatedProxy`. Empty tuple when no auto-expansion occurred.
400
+ Populated at decoration time; read by audit tools to distinguish user-supplied mappings from
401
+ auto-generated ones.
402
+ args_mapping_positional_only: ``args_mapping`` old-key names whose remapped target name is a
403
+ POSITIONAL_ONLY parameter in the target class constructor. Calling the proxy with such
404
+ keys as keyword arguments would raise ``TypeError`` without the positional split applied
405
+ by the proxy call path (see :attr:`target_positional_only`). Empty tuple when all
406
+ remapped targets are kwarg-accessible. Populated at decoration time; surfaced by
407
+ :func:`~deprecate.audit.validate_mapping_compatibility`.
408
+ target_positional_only: Names of POSITIONAL_ONLY parameters on the forwarding target callable
409
+ used with :func:`~deprecate.deprecated`, including ``self`` and ``cls`` when they are
410
+ declared positional-only. Non-empty when a ``@deprecated(target=fn)`` call found ``fn``
411
+ declares at least one positional-only parameter. ``self`` and ``cls`` are excluded from
412
+ the :class:`UserWarning` message but included here so the split-dispatch gate fires even
413
+ when the only positional-only parameter is the instance or class receiver (e.g.
414
+ ``def __init__(self, /): ...``). The call dispatcher splits these out of
415
+ ``resolved_kwargs`` and forwards them positionally so the target call does not raise
416
+ ``TypeError``. For :class:`~deprecate.proxy._DeprecatedProxy` objects this holds the
417
+ POSITIONAL_ONLY parameter names of the *active* class constructor (target class when
418
+ configured, wrapped class otherwise) so the proxy call path can apply the same
419
+ positional split (see also :attr:`args_mapping_positional_only`). Empty frozenset
420
+ for non-callable targets.
421
+ target_positional_only_order: Full parameter-name sequence of the forwarding target callable,
422
+ in declaration order. Pre-computed at decoration time alongside
423
+ :attr:`target_positional_only` so the call dispatcher can iterate in declaration order
424
+ without calling ``inspect.signature`` on every dispatch. Not included in ``repr``.
425
+ Empty tuple when ``target_positional_only`` is empty.
426
+ source_positional_only: Names of POSITIONAL_ONLY parameters declared by the decorated
427
+ *source* callable itself. The wrapper converts positional args to kwargs internally,
428
+ so whenever the dispatcher invokes the source body (NOTIFY, ARGS_REMAP, and the
429
+ migrated-caller short-circuit) it must split these names back out of the resolved
430
+ kwargs and pass them positionally — otherwise every call would raise ``TypeError``.
431
+ Mirrors :attr:`target_positional_only` on the source side. Empty frozenset when the
432
+ source declares no ``/``.
433
+ source_positional_only_order: Full parameter-name sequence of the decorated source in
434
+ declaration order; the source-side twin of :attr:`target_positional_only_order`.
435
+ Not included in ``repr``. Empty tuple when :attr:`source_positional_only` is empty.
436
+ source_var_positional_prefix: Number of named positional parameters declared before the
437
+ source's ``*args``. Used by the forwarding dispatcher to compute the surplus
438
+ positional tail (``args[prefix:]``) that must be forwarded to a callable target
439
+ rather than silently dropped. ``0`` when the source declares no var-positional
440
+ parameter.
441
+ target_all_param_names: All parameter names of the forwarding target callable (including any
442
+ ``*args`` / ``**kwargs`` names), pre-computed at decoration time so the call-time kwarg
443
+ validation in :func:`~deprecate.deprecation._prepare_target_call` does not re-inspect the
444
+ target on every forwarded call. ``None`` when facts are not precomputed (manual
445
+ ``DeprecationConfig`` construction or non-callable target); ``frozenset()`` for zero-arg
446
+ callables. Internal call-time cache — excluded from ``repr`` and equality so audit output
447
+ and stored-config comparisons stay stable.
448
+ target_accepts_var_positional: ``True`` when the forwarding target declares ``*args``. Pre-computed
449
+ decoration-time replacement for the per-call ``inspect.getfullargspec`` probe. Internal cache —
450
+ excluded from ``repr`` and equality.
451
+ target_accepts_var_keyword: ``True`` when the forwarding target declares ``**kwargs``. Pre-computed
452
+ decoration-time replacement for the per-call ``inspect.getfullargspec`` probe. Internal cache —
453
+ excluded from ``repr`` and equality.
454
+
455
+ Note:
456
+ ``@dataclass(frozen=True)`` blocks attribute *rebinding* on the config object itself, but the
457
+ stored ``args_mapping`` and ``attrs_mapping`` dicts remain mutable. Code that reads these fields
458
+ must not modify them in place; the decorator copies them defensively at decoration time.
459
+
460
+ """
461
+
462
+ deprecated_in: str = ""
463
+ remove_in: str = ""
464
+ name: str = ""
465
+ target: Optional[Union[Callable[..., Any], "TargetMode"]] = None
466
+ args_mapping: Optional[dict[str, Optional[str]]] = None
467
+ args_extra: Optional[dict[str, Any]] = None
468
+ misconfigured: bool = False
469
+ docstring_style: Literal["rst", "mkdocs"] = "rst"
470
+ template_mgs: Optional[str] = None
471
+ attrs_mapping: Optional[dict[str, Optional[str]]] = None
472
+ args_mapping_auto_expanded: tuple[str, ...] = field(default_factory=tuple)
473
+ args_mapping_positional_only: tuple[str, ...] = field(default_factory=tuple)
474
+ target_positional_only: frozenset[str] = field(default_factory=frozenset)
475
+ target_positional_only_order: tuple[str, ...] = field(default_factory=tuple, repr=False)
476
+ source_positional_only: frozenset[str] = field(default_factory=frozenset)
477
+ source_positional_only_order: tuple[str, ...] = field(default_factory=tuple, repr=False)
478
+ source_var_positional_prefix: int = 0
479
+ target_all_param_names: Optional[frozenset[str]] = field(default=None, repr=False, compare=False)
480
+ target_accepts_var_positional: bool = field(default=False, repr=False, compare=False)
481
+ target_accepts_var_keyword: bool = field(default=False, repr=False, compare=False)
482
+
483
+
484
+ @runtime_checkable
485
+ class _HasDeprecationMeta(Protocol):
486
+ """Structural type for any callable that carries ``__deprecated__`` metadata.
487
+
488
+ Both ``@deprecated``-decorated functions and :class:`~deprecate.proxy._DeprecatedProxy` instances satisfy this
489
+ protocol once the decorator has been applied.
490
+
491
+ Used as a TypeGuard target so that a ``hasattr`` guard narrows the type of an arbitrary callable to one whose
492
+ ``__deprecated__`` attribute is typed — eliminating the need for a ``cast`` after the guard.
493
+
494
+ """
495
+
496
+ __deprecated__: DeprecationConfig
497
+ __name__: str
498
+
499
+ def __call__(self, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401
500
+ """Call the deprecated object."""
501
+ raise NotImplementedError
502
+
503
+
504
+ def _has_deprecation_meta(obj: Any) -> "TypeGuard[_HasDeprecationMeta]": # noqa: ANN401
505
+ """Return ``True`` if *obj* carries typed :class:`~deprecate._types.DeprecationConfig` metadata.
506
+
507
+ Using this as a guard narrows the type of *obj* from ``Any`` / ``Callable`` to
508
+ :class:`~deprecate._types._HasDeprecationMeta`,
509
+ allowing direct typed access to ``obj.__deprecated__`` without a ``cast``.
510
+
511
+ Args:
512
+ obj: Any object to test.
513
+
514
+ Returns:
515
+ ``True`` if ``__deprecated__`` exists and is a :class:`~deprecate._types.DeprecationConfig`;
516
+ ``False`` otherwise.
517
+
518
+ """
519
+ # ``getattr(..., default)`` only swallows ``AttributeError``; a foreign object encountered during a
520
+ # recursive audit scan whose ``__getattr__``/``__getattribute__`` raises something else (e.g. a lazy
521
+ # proxy raising ``RuntimeError``) would otherwise crash the whole scan. Treat any failure as "no meta".
522
+ try:
523
+ meta = getattr(obj, "__deprecated__", None)
524
+ except Exception:
525
+ return False
526
+ return isinstance(meta, DeprecationConfig)
527
+
528
+
529
+ @dataclass
530
+ class _ProxyConfig:
531
+ """Private mutable runtime state for :class:`~deprecate.proxy._DeprecatedProxy`.
532
+
533
+ This is an internal type — not exported from the package and not referenced outside of :mod:`deprecate.proxy`.
534
+
535
+ Attributes:
536
+ obj: The wrapped (source) object.
537
+ stream: Callable used to emit warnings, or ``None`` to suppress them.
538
+ num_warns: Maximum number of warnings to emit; ``-1`` means unlimited.
539
+ read_only: When ``True``, write operations through the proxy raise :class:`AttributeError`.
540
+ args_extra: Optional dict of extra keyword arguments merged into forwarded calls after ``args_mapping`` has
541
+ been applied. Ignored when the proxy is in :attr:`~deprecate._types.TargetMode.NOTIFY` mode.
542
+ template_mgs: Optional custom warning-message template (``%``-style placeholders) that overrides the built-in
543
+ templates at warn time. ``None`` (default) keeps the built-in templates. See
544
+ :func:`~deprecate.proxy.deprecated_class` for the placeholder catalogue.
545
+ attrs_mapping: Optional mapping of deprecated attribute names to their canonical replacement names (or
546
+ ``None`` for warn-only). When set, the proxy emits warnings only on access to listed names and forwards
547
+ all other reads/writes/deletes silently. See :func:`~deprecate.proxy.deprecated_class` for full semantics.
548
+ warned: Mutable counter tracking how many global (callable-level) warnings have been emitted so far.
549
+ warned_args: Per-argument warning counts for argument-level deprecations. Keys are deprecated argument names;
550
+ values are emission counts.
551
+ lock: Guards the warn-quota check-then-act sequence (read counter → decide to emit → increment) so that
552
+ concurrent first accesses cannot all pass the ``num_warns`` gate and each emit a warning. Excluded from
553
+ ``repr`` and equality — it is runtime machinery, not state identity. A fresh lock is created on copy /
554
+ deepcopy rather than transferring the original mutex state.
555
+
556
+ """
557
+
558
+ obj: Any
559
+ stream: Optional[Callable[..., None]]
560
+ num_warns: int
561
+ read_only: bool
562
+ args_extra: Optional[dict[str, Any]] = None
563
+ template_mgs: Optional[str] = None
564
+ attrs_mapping: Optional[dict[str, Optional[str]]] = None
565
+ warned: int = 0
566
+ warned_args: dict[str, int] = field(default_factory=dict)
567
+ lock: threading.Lock = field(default_factory=threading.Lock, repr=False, compare=False)
568
+
569
+ def __deepcopy__(self, memo: dict[int, Any]) -> "_ProxyConfig":
570
+ return replace(
571
+ self,
572
+ obj=copy.deepcopy(self.obj, memo),
573
+ warned_args=copy.deepcopy(self.warned_args, memo),
574
+ lock=threading.Lock(), # fresh lock — mutex state is not transferable
575
+ )
576
+
577
+ def __getstate__(self) -> dict[str, Any]:
578
+ return {k: v for k, v in self.__dict__.items() if k != "lock"}
579
+
580
+ def __setstate__(self, state: dict[str, Any]) -> None:
581
+ self.__dict__.update(state)
582
+ self.lock = threading.Lock() # fresh lock — mutex state is not transferable
583
+
584
+
585
+ @dataclass
586
+ class _WrapperState:
587
+ """Private mutable runtime state for ``@deprecated``-decorated callables.
588
+
589
+ This is an internal type — not exported from the package and not referenced outside of :mod:`deprecate.deprecation`.
590
+
591
+ Attributes:
592
+ called: Total invocation count, including calls where the warning was suppressed.
593
+ warned_calls: Number of callable-level deprecation warnings emitted so far.
594
+ warned_args: Per-argument warning counts for argument-level deprecations. Keys are deprecated argument names;
595
+ values are emission counts.
596
+ warned_misconfigured: ``True`` after the one-time misconfiguration UserWarning has been emitted at call time.
597
+ lock: Guards the warn-quota check-then-act sequence (read counter → decide to emit → increment) so that
598
+ concurrent first calls cannot all pass the ``num_warns`` gate and each emit a warning. Only the warn
599
+ path takes this lock; the ``called`` counter is a best-effort diagnostic and stays lock-free. Excluded
600
+ from ``repr`` and equality — it is runtime machinery, not state identity.
601
+
602
+ """
603
+
604
+ called: int = 0
605
+ warned_calls: int = 0
606
+ warned_args: dict[str, int] = field(default_factory=dict)
607
+ warned_misconfigured: bool = False
608
+ lock: threading.Lock = field(default_factory=threading.Lock, repr=False, compare=False)
609
+
610
+
611
+ @runtime_checkable
612
+ class _DeprecatedCallable(Protocol):
613
+ """Structural type for a ``@deprecated``-decorated callable with mutable runtime state.
614
+
615
+ This protocol describes the shape of a function or method after the ``@deprecated`` decorator has been applied. It
616
+ includes both static metadata (``__deprecated__``) and mutable runtime state (``_state``).
617
+
618
+ Used to type-safely access ``_state`` on decorated callables without casting.
619
+
620
+ """
621
+
622
+ __deprecated__: DeprecationConfig
623
+ _state: _WrapperState
624
+
625
+ def __call__(self, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401
626
+ """Call the deprecated callable."""
627
+ raise NotImplementedError
628
+
629
+
630
+ @dataclass
631
+ class _CallPlan:
632
+ """Resolved dispatch plan returned by :func:`deprecate.deprecation._build_call_plan`.
633
+
634
+ Captures the outcome of all decision-making shared between the sync and async wrappers in :func:`deprecated`: state
635
+ mutation, kwargs assembly, warning emission, target resolution. The wrapper consumes this struct to decide whether
636
+ to invoke ``source`` or a forwarded target callable, and with which kwargs shape.
637
+
638
+ Attributes:
639
+ short_circuit: ``True`` when the wrapper must call ``source`` directly (no warning, no remap, no target
640
+ lookup) — this is the "migrated caller using the new arg name" fast path before any warning logic runs.
641
+ The wrapper calls ``source(**resolved_kwargs)`` for sources without ``*args``, or
642
+ ``source(*args, **original_kwargs)`` when the source declares a var-positional parameter so that
643
+ extra positional arguments are forwarded correctly. When ``True``, :attr:`resolved_kwargs` equals the
644
+ kwargs after :func:`_update_kwargs_with_args`, before defaults / remap / extras are applied.
645
+ original_kwargs: A shallow copy of the wrapper's incoming ``kwargs`` (before positional args were converted to
646
+ keyword form). Used by the var-positional branch when no argument-rename reason fired, so that the source
647
+ sees its original positional/keyword shape.
648
+ resolved_kwargs: Final kwargs after defaults injection, ``args_mapping`` remap, and ``args_extra`` merge when
649
+ the normal planning path runs. On the :attr:`short_circuit` path, this instead holds the kwargs produced
650
+ immediately after :func:`_update_kwargs_with_args`, and that is what the wrapper passes to ``source``.
651
+ reason_argument: Subset of ``args_mapping`` whose old-arg names appeared in the caller's kwargs. Non-empty
652
+ value means the argument-rename warning fired (or was suppressed by ``num_warns`` quota). Empty when the
653
+ warning reason was callable-deprecation or when no rename was triggered.
654
+ target_func: Resolved target callable when forwarding is required, or ``None`` when the source body should be
655
+ invoked instead. ``None`` for :attr:`TargetMode.NOTIFY` and :attr:`TargetMode.ARGS_REMAP`; a validated
656
+ callable when the user passed a forwarding target.
657
+
658
+ """
659
+
660
+ short_circuit: bool
661
+ original_kwargs: dict[str, Any]
662
+ resolved_kwargs: dict[str, Any]
663
+ reason_argument: dict[str, Optional[str]] = field(default_factory=dict)
664
+ target_func: Optional[Callable[..., Any]] = None
.venv/lib/python3.12/site-packages/deprecate/audit.py ADDED
@@ -0,0 +1,1537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audit tools for deprecation lifecycle management.
2
+
3
+ This module provides several complementary utilities for verifying the health of deprecated callables across a
4
+ codebase. All are designed to be called from pytest or a CI script against an imported package.
5
+
6
+ **Wrapper configuration** (:func:`~deprecate.audit.validate_deprecation_wrapper`,
7
+ :func:`~deprecate.audit.find_deprecation_wrappers`):
8
+ Detect wrappers that have zero impact — invalid ``args_mapping`` keys, identity mappings, empty mappings, or a
9
+ ``target`` pointing back to the same wrapper.
10
+
11
+ **Mapping compatibility** (:func:`~deprecate.audit.validate_mapping_compatibility`):
12
+ Detect :func:`~deprecate.proxy.deprecated_class` wrappers whose ``args_mapping`` remaps to POSITIONAL_ONLY
13
+ constructor params, silently degrading to ``setattr`` at call time.
14
+
15
+ **Expiry enforcement** (:func:`~deprecate.audit.validate_deprecation_expiry`):
16
+ Detect wrappers whose ``remove_in`` version has been reached or passed, preventing zombie code from shipping past
17
+ its scheduled removal deadline.
18
+
19
+ **Chain detection** (:func:`~deprecate.audit.validate_deprecation_chains`):
20
+ Detect wrappers whose ``target`` is itself a deprecated callable, forming a chain that users traverse
21
+ unnecessarily. Two chain kinds are reported via :class:`~deprecate.audit.ChainType`: ``TARGET`` (forwarding chain)
22
+ and ``STACKED`` (composed argument or attribute mappings).
23
+
24
+ **Report generation** (:func:`~deprecate.audit.generate_deprecation_table`):
25
+ Generate a docs-friendly markdown summary from wrapper metadata.
26
+
27
+ Results are returned as :class:`~deprecate.audit.DeprecationWrapperInfo` dataclasses, which carry both
28
+ identification info and structured validation results for programmatic processing.
29
+
30
+ !!! note
31
+ :func:`~deprecate.audit.validate_deprecation_expiry` requires the ``packaging`` library for PEP 440
32
+ version comparison. Install with: ``pip install pyDeprecate[audit]``
33
+
34
+ Copyright (C) 2020-2026 Jiri Borovec <6035284+Borda@users.noreply.github.com>
35
+
36
+ """
37
+
38
+ # Note: Proxy objects are discoverable via the generic ``callable(obj)`` +
39
+ # ``hasattr(obj, "__deprecated__")`` scan in :func:`find_deprecation_wrappers` and
40
+ # :func:`validate_deprecation_expiry`. The ``__deprecated__`` schema is now unified
41
+ # across ``@deprecated`` and :class:`~deprecate.proxy._DeprecatedProxy` via
42
+ # :class:`~deprecate._types.DeprecationConfig` — both always populate the ``name`` field,
43
+ # so ``validate_deprecation_wrapper`` can read it correctly for proxy objects too.
44
+
45
+ import enum
46
+ import importlib
47
+ import importlib.metadata
48
+ import inspect
49
+ import pkgutil
50
+ import re
51
+ import warnings
52
+ from contextlib import suppress
53
+ from dataclasses import dataclass, field, is_dataclass, replace
54
+ from enum import Enum
55
+ from functools import cached_property, wraps
56
+ from typing import TYPE_CHECKING, Any, Callable, Optional, Union
57
+
58
+ if TYPE_CHECKING:
59
+ from packaging.version import Version
60
+
61
+ from deprecate._types import DeprecationConfig, TargetMode, _has_deprecation_meta
62
+ from deprecate.deprecation import _DeprecatedProperty
63
+ from deprecate.proxy import _DeprecatedProxy, deprecated_class
64
+ from deprecate.utils import get_func_arguments_types_defaults
65
+
66
+
67
+ class TableStyle(str, enum.Enum):
68
+ """Markdown table layout produced by :func:`~deprecate.audit.generate_deprecation_table`."""
69
+
70
+ COMPACT = "compact"
71
+ MATRIX = "matrix"
72
+
73
+
74
+ class DeprecationStatus(str, enum.Enum):
75
+ """Lifecycle status labels used in the deprecation report's *Current Status* column.
76
+
77
+ Each member's value is the full display string (emoji + text) rendered in the table.
78
+ Using a ``str`` enum means members compare equal to their string values and can be
79
+ returned wherever a plain string is expected.
80
+
81
+ Members are *declared* from least to most urgent for readability, but this enum is **not orderable by
82
+ urgency**: because each value starts with an emoji, the inherited ``str`` ordering operators (``<``, ``>``)
83
+ compare Unicode codepoints of those emoji, not deprecation urgency. Do not rely on ``status_a > status_b``
84
+ to mean "more urgent" — compare members explicitly (``status is DeprecationStatus.PAST_REMOVAL_DATE``).
85
+ The ordering operators are overridden to raise ``TypeError`` so accidental comparisons fail loudly.
86
+
87
+ Examples:
88
+ >>> DeprecationStatus.ACTIVE_WARNING.value
89
+ '📢 Deprecation Active'
90
+ >>> DeprecationStatus.PAST_REMOVAL_DATE is DeprecationStatus.PAST_REMOVAL_DATE
91
+ True
92
+
93
+ """
94
+
95
+ SCHEDULED_DEPRECATION = "🕒 Scheduled Deprecation" # current < deprecated_in
96
+ NO_REMOVAL_TARGET = "ℹ️ No Removal Target" # remove_in not set
97
+ STATUS_UNKNOWN = "⚪ Status Unknown" # current_version unavailable
98
+ INVALID_REMOVAL_TARGET = "⚪ Invalid Removal Target" # remove_in unparsable
99
+ ACTIVE_WARNING = "📢 Deprecation Active" # current < remove_in (different base)
100
+ REMOVAL_IMMINENT = "⏰ Removal Imminent" # pre-release dev/a/b of remove_in base
101
+ REMOVE_BEFORE_RELEASE = "🔔 Remove Before Release" # RC of the remove_in base release
102
+ PAST_REMOVAL_DATE = "💥 Past Removal Date" # current >= remove_in
103
+
104
+ def __lt__(self, other: object) -> bool:
105
+ """Raise TypeError — urgency ordering is not meaningful for emoji-valued status labels."""
106
+ raise TypeError("'<' not supported between instances of 'DeprecationStatus' — compare by identity")
107
+
108
+ def __le__(self, other: object) -> bool:
109
+ """Raise TypeError — urgency ordering is not meaningful for emoji-valued status labels."""
110
+ raise TypeError("'<=' not supported between instances of 'DeprecationStatus' — compare by identity")
111
+
112
+ def __gt__(self, other: object) -> bool:
113
+ """Raise TypeError — urgency ordering is not meaningful for emoji-valued status labels."""
114
+ raise TypeError("'>' not supported between instances of 'DeprecationStatus' — compare by identity")
115
+
116
+ def __ge__(self, other: object) -> bool:
117
+ """Raise TypeError — urgency ordering is not meaningful for emoji-valued status labels."""
118
+ raise TypeError("'>=' not supported between instances of 'DeprecationStatus' — compare by identity")
119
+
120
+
121
+ def _normalize_version_string(version: str) -> str:
122
+ """Normalize non-standard version strings before PEP 440 parsing.
123
+
124
+ Newer ``packaging`` (>=22) is strict PEP 440 and rejects real-world strings that omit trailing digits
125
+ on pre/post/dev release labels (e.g. ``"1.8.0.dev"``, ``"1.8.0dev"``, ``"1.8.0.post"``). This helper
126
+ performs the minimum normalization needed to make such strings parseable, then defers everything else
127
+ (label aliasing like ``alpha`` -> ``a``, case folding, separator handling) to ``packaging.Version``.
128
+
129
+ The transformation is conservative:
130
+
131
+ 1. Strip a single leading ``v`` or ``V`` prefix (left-anchored, so only one leading ``v`` is removed).
132
+ 2. Append ``0`` to bare pre/post/dev labels that lack a trailing digit. Labels recognized:
133
+ ``dev``, ``rc``, ``a``, ``b``, ``c``, ``alpha``, ``beta``, ``preview``, ``post``.
134
+
135
+ The label normalization runs only over the *public* part of the version — any PEP 440 local segment
136
+ (everything after ``+``) is split off first and re-attached verbatim, so a legitimate local like
137
+ ``1.2.3+cuda`` is never mangled into ``1.2.3+cuda0`` by the trailing-``a`` label rule.
138
+
139
+ No other transformations are applied — case, separators, and label aliases pass through unchanged
140
+ so ``packaging.Version`` can apply its own canonicalization.
141
+
142
+ Args:
143
+ version: Raw version string, possibly missing trailing digits on labels.
144
+
145
+ Returns:
146
+ Normalized version string ready to be passed to ``packaging.version.Version``.
147
+
148
+ Examples:
149
+ >>> _normalize_version_string("1.8.0.dev")
150
+ '1.8.0.dev0'
151
+ >>> _normalize_version_string("1.8.0dev")
152
+ '1.8.0dev0'
153
+ >>> _normalize_version_string("1.8.0.post")
154
+ '1.8.0.post0'
155
+ >>> _normalize_version_string("v1.2.3")
156
+ '1.2.3'
157
+ >>> _normalize_version_string("1.8.0.RC1")
158
+ '1.8.0.RC1'
159
+ >>> _normalize_version_string("1.2.3")
160
+ '1.2.3'
161
+ >>> _normalize_version_string("1.2.3+cuda")
162
+ '1.2.3+cuda'
163
+ >>> _normalize_version_string("v1.8.0.dev+local.a")
164
+ '1.8.0.dev0+local.a'
165
+
166
+ """
167
+ # Split off any PEP 440 local segment (after ``+``) so the label regex never touches it; labels like
168
+ # ``post``/``dev`` never appear in a local segment, and running the rule over it mangles legit locals.
169
+ public, plus, local = version.partition("+")
170
+ # Strip a single left-anchored leading ``v``/``V`` (``lstrip("vV")`` would strip *all* leading v's).
171
+ normalized = re.sub(r"^[vV]", "", public)
172
+ # Append ``0`` to bare pre/post/dev labels with no trailing digit. The ordering of the alternatives
173
+ # matters: longer labels (``alpha``, ``beta``, ``preview``) must come before their single-letter
174
+ # forms (``a``, ``b``) so the regex prefers the longer match.
175
+ # Use a negative lookahead for ``[0-9]`` to detect "no trailing digit"; ``(?=$|[^A-Za-z0-9])``
176
+ # ensures the label is a whole token (e.g. ``dev`` but not ``develop``).
177
+ pattern = re.compile(
178
+ r"(?P<sep>\.?)(?P<label>alpha|beta|preview|post|dev|rc|a|b|c)(?![A-Za-z0-9])",
179
+ re.IGNORECASE,
180
+ )
181
+ normalized = pattern.sub(lambda m: f"{m.group('sep')}{m.group('label')}0", normalized)
182
+ return f"{normalized}{plus}{local}"
183
+
184
+
185
+ def _parse_version(version_string: str) -> "Version":
186
+ """Parse a version string using the packaging library (PEP 440 compliant).
187
+
188
+ This function requires the 'packaging' library, which is available as an optional dependency via the 'audit'
189
+ extra: ``pip install pyDeprecate[audit]``
190
+
191
+ The packaging library provides robust PEP 440 version parsing and comparison, supporting pre-releases
192
+ (alpha/beta/rc), stable releases, post-releases, and development releases with proper ordering.
193
+
194
+ Inputs are first passed through :func:`_normalize_version_string`, which appends ``0`` to bare
195
+ pre/post/dev labels (e.g. ``"1.8.0.dev"`` becomes ``"1.8.0.dev0"``) so non-canonical-but-common
196
+ strings parse successfully under strict ``packaging`` (>=22).
197
+
198
+ Args:
199
+ version_string: Version string (e.g., "1.2.3", "2.0", "1.5.0a1", "1.5.0rc1", "1.5.0.post1").
200
+
201
+ Returns:
202
+ packaging.version.Version object that supports comparison operations.
203
+
204
+ Raises:
205
+ ImportError: If the packaging library is not installed.
206
+ ValueError: If the version string is not valid per PEP 440
207
+ (wraps ``packaging.version.InvalidVersion`` with additional context).
208
+
209
+ Example:
210
+ >>> import importlib; importlib.import_module("packaging") # doctest: +ELLIPSIS
211
+ <module 'packaging' ...>
212
+ >>> v1 = _parse_version("1.2.3")
213
+ >>> v2 = _parse_version("2.0")
214
+ >>> v1 < v2
215
+ True
216
+ >>> _parse_version("1.5.0a1") < _parse_version("1.5.0")
217
+ True
218
+ >>> _parse_version("1.8.0.dev") < _parse_version("1.8.0")
219
+ True
220
+ >>> _parse_version("1.8.0.post") > _parse_version("1.8.0")
221
+ True
222
+
223
+ !!! note
224
+ Install the audit extra to use version comparison features:
225
+ ``pip install pyDeprecate[audit]``
226
+
227
+ """
228
+ try:
229
+ from packaging.version import InvalidVersion, Version
230
+ except ImportError as err:
231
+ raise ImportError(
232
+ "Version comparison requires the 'packaging' library. Install with: pip install pyDeprecate[audit]"
233
+ ) from err
234
+
235
+ try:
236
+ return Version(_normalize_version_string(version_string))
237
+ except InvalidVersion as err:
238
+ raise ValueError(
239
+ f"Failed to parse version '{version_string}'. Expected PEP 440 format "
240
+ f"(e.g., '1.2.3', '2.0', '1.5.0a1'). Error: {err}"
241
+ ) from err
242
+
243
+
244
+ class ChainType(Enum):
245
+ """Type of deprecation chain detected by :func:`~deprecate.audit.validate_deprecation_chains`.
246
+
247
+ Attributes:
248
+ TARGET: The ``target`` argument is itself a callable decorated with :func:`~deprecate.deprecated`
249
+ (a forwarding chain). Fix by pointing directly to the final non-deprecated target.
250
+ STACKED: Arg mappings chain and must be composed/collapsed. Two sub-cases:
251
+ (a) Callable ``target`` is itself ``@deprecated(True, args_mapping=...)`` — the
252
+ caller's mapping feeds into the target's self-renaming, so both hops must be
253
+ collapsed into one. (b) Multiple ``@deprecated(True, args_mapping=...)`` decorators
254
+ are stacked on the same function and should be merged into a single decorator.
255
+ Also used when ``attrs_mapping`` values point at another deprecated attribute alias.
256
+
257
+ """
258
+
259
+ TARGET = "target"
260
+ STACKED = "stacked"
261
+
262
+
263
+ @dataclass(frozen=True)
264
+ class DeprecationWrapperInfo:
265
+ """Information about a deprecated wrapper and its validation results.
266
+
267
+ This dataclass represents a deprecated wrapper (a :func:`~deprecate.deprecated`-decorated function or a
268
+ :func:`~deprecate.proxy.deprecated_class`/:func:`~deprecate.proxy.deprecated_instance` proxy), containing both
269
+ identification info and validation results from :func:`~deprecate.audit.validate_deprecation_wrapper` or
270
+ :func:`~deprecate.audit.find_deprecation_wrappers`.
271
+
272
+ Attributes:
273
+ module: Module name where the wrapper is defined (empty for direct validation).
274
+ function: Wrapper name.
275
+ deprecated_info: The ``__deprecated__`` attribute from the decorator,
276
+ as a :class:`~deprecate._types.DeprecationConfig`.
277
+ invalid_args: List of ``args_mapping`` keys that don't exist in the wrapper's signature.
278
+ empty_args_mapping: True if ``args_mapping`` is None or empty (no argument remapping).
279
+ identity_args_mapping: List of args where key equals value (e.g., ``{'arg': 'arg'}``).
280
+ self_reference: True if target points to the same wrapper.
281
+ no_effect: True if wrapper has zero impact (combines all checks).
282
+ all_identity: True when every configured mapping is an identity mapping (key == value, non-empty).
283
+ chain_type: The kind of deprecation chain detected, or ``None`` if no chain.
284
+ See :class:`~deprecate.audit.ChainType` for values
285
+ (:attr:`~deprecate.audit.ChainType.TARGET` or :attr:`~deprecate.audit.ChainType.STACKED`).
286
+ misconfigured_target: True when the wrapper has an invalid target configuration:
287
+ ``target=False``, :attr:`~deprecate._types.TargetMode.NOTIFY` with ``args_mapping``, or
288
+ :attr:`~deprecate._types.TargetMode.ARGS_REMAP` with empty ``args_mapping``.
289
+ empty_deprecated_in: True when ``deprecated_in`` is empty. Missing ``remove_in`` alone is a valid use case
290
+ (many libraries deprecate without a scheduled removal date), so only the absence of ``deprecated_in``
291
+ is treated as a misconfiguration signal. CI pipelines can filter on this field to surface wrappers
292
+ that lack the introductory version metadata without crashing callers.
293
+ api_type: Inferred deprecated API type for report generation.
294
+ Possible values: ``callable``, ``args``, ``class``, ``dataclass``, ``dataclass attributes``,
295
+ ``data``, ``class constructor``, ``class constructor args``, ``class method``, ``class method args``,
296
+ ``classmethod``, ``classmethod args``, ``staticmethod``, ``staticmethod args``.
297
+ args_mapping_auto_expanded: ``args_mapping`` keys that were automatically copied from ``attrs_mapping``
298
+ by the dataclass dual-surface expansion at decoration time. Empty list when no auto-expansion
299
+ occurred. Read from :attr:`~deprecate._types.DeprecationConfig.args_mapping_auto_expanded`.
300
+ args_mapping_positional_only: ``args_mapping`` old-key names whose remapped target is a POSITIONAL_ONLY
301
+ constructor parameter. Non-empty list signals that the proxy falls back to ``setattr`` for those
302
+ keys. Use :func:`~deprecate.audit.validate_mapping_compatibility` to filter wrappers by this
303
+ field. Read from :attr:`~deprecate._types.DeprecationConfig.args_mapping_positional_only`.
304
+ inner_order_property: ``True`` when the wrapper is a plain :class:`property` whose ``fget`` carries
305
+ ``@deprecated`` metadata — the *inner order* ``@property @deprecated`` (``@deprecated`` closer to
306
+ ``def``). In this order only ``fget`` warns; any setter or deleter added afterwards is built from the
307
+ plain :class:`property` base and is silently unprotected. The flag fires for every inner-order
308
+ property, including the getter-only shape, because the canonical order is the outer
309
+ ``@deprecated(...) @property`` (which produces a :class:`~deprecate.deprecation._DeprecatedProperty`
310
+ that re-wraps every rebound accessor). CI pipelines can filter on this field to reject the silent
311
+ write/delete gap. ``False`` for outer-order properties, non-property wrappers, and proxies.
312
+
313
+ Example:
314
+ >>> info = DeprecationWrapperInfo(
315
+ ... module="my_package.module",
316
+ ... function="old_function",
317
+ ... deprecated_info=DeprecationConfig(deprecated_in="1.0", remove_in="2.0"),
318
+ ... invalid_args=["nonexistent"],
319
+ ... no_effect=True,
320
+ ... )
321
+ >>> info.function
322
+ 'old_function'
323
+ >>> info.invalid_args
324
+ ['nonexistent']
325
+
326
+ """
327
+
328
+ module: str = ""
329
+ function: str = ""
330
+ deprecated_info: DeprecationConfig = field(default_factory=DeprecationConfig)
331
+ invalid_args: list[str] = field(default_factory=list)
332
+ empty_args_mapping: bool = False
333
+ identity_args_mapping: list[str] = field(default_factory=list)
334
+ self_reference: bool = False
335
+ no_effect: bool = False
336
+ misconfigured_target: bool = False
337
+ all_identity: bool = False
338
+ chain_type: Optional[ChainType] = None
339
+ empty_deprecated_in: bool = field(init=False, default=False)
340
+ api_type: str = field(repr=False, default="")
341
+ args_mapping_auto_expanded: list[str] = field(default_factory=list)
342
+ args_mapping_positional_only: list[str] = field(default_factory=list)
343
+ inner_order_property: bool = False
344
+
345
+ def __post_init__(self) -> None:
346
+ """Derive ``empty_deprecated_in`` from ``deprecated_info`` to keep them in sync."""
347
+ object.__setattr__(self, "empty_deprecated_in", not self.deprecated_info.deprecated_in)
348
+
349
+ @property
350
+ def empty_mapping(self) -> bool:
351
+ """Deprecated alias for :attr:`~deprecate.audit.DeprecationWrapperInfo.empty_args_mapping`.
352
+
353
+ !!! warning "Deprecated in 0.8"
354
+ Renamed to :attr:`~deprecate.audit.DeprecationWrapperInfo.empty_args_mapping`.
355
+ Will be removed in v1.0.
356
+
357
+ Note:
358
+ Python's default warning filter deduplicates per ``(message, category, module, lineno)``,
359
+ so accessing this property in a loop from the same call site emits at most one warning.
360
+
361
+ """
362
+ warnings.warn(
363
+ "'empty_mapping' was renamed to 'empty_args_mapping' in 0.8 and will be removed in 1.0.",
364
+ DeprecationWarning,
365
+ stacklevel=2,
366
+ )
367
+ return self.empty_args_mapping
368
+
369
+ @property
370
+ def identity_mapping(self) -> list[str]:
371
+ """Deprecated alias for :attr:`~deprecate.audit.DeprecationWrapperInfo.identity_args_mapping`.
372
+
373
+ !!! warning "Deprecated in 0.8"
374
+ Renamed to :attr:`~deprecate.audit.DeprecationWrapperInfo.identity_args_mapping`.
375
+ Will be removed in v1.0.
376
+
377
+ Note:
378
+ Python's default warning filter deduplicates per ``(message, category, module, lineno)``,
379
+ so accessing this property in a loop from the same call site emits at most one warning.
380
+
381
+ """
382
+ warnings.warn(
383
+ "'identity_mapping' was renamed to 'identity_args_mapping' in 0.8 and will be removed in 1.0.",
384
+ DeprecationWarning,
385
+ stacklevel=2,
386
+ )
387
+ return self.identity_args_mapping
388
+
389
+
390
+ # ---------------------------------------------------------------------------
391
+ # Backward-compatible constructor shim for DeprecationWrapperInfo
392
+ #
393
+ # ``empty_mapping`` and ``identity_mapping`` were renamed to
394
+ # ``empty_args_mapping`` / ``identity_args_mapping`` in 0.8. The
395
+ # ``@property`` aliases above cover attribute *reads*; this shim patches
396
+ # ``__init__`` so old keyword arguments emit ``DeprecationWarning`` and are
397
+ # redirected to the new names rather than raising ``TypeError``.
398
+ #
399
+ # dataclasses.replace() merges all current field values with the caller's
400
+ # changes before calling ``cls(**merged)``. Passing an old name (e.g.
401
+ # ``replace(info, empty_mapping=True)``) injects the old kwarg alongside
402
+ # the auto-copied ``empty_args_mapping`` value. The shim detects that
403
+ # conflict and honours the old-name value (discards the auto-injected one).
404
+ #
405
+ # ADD field → add @property alias above + (old, new) pair in _dwi_compat_init.
406
+ # RENAME/REMOVE field → update _dwi_compat_init accordingly.
407
+ # ---------------------------------------------------------------------------
408
+ _dwi_orig_init = DeprecationWrapperInfo.__init__
409
+
410
+
411
+ @wraps(_dwi_orig_init)
412
+ def _dwi_compat_init(self: DeprecationWrapperInfo, *args: object, **kwargs: object) -> None:
413
+ """Wrap the auto-generated ``__init__`` to accept legacy constructor kwargs."""
414
+ for old, new in (
415
+ ("empty_mapping", "empty_args_mapping"),
416
+ ("identity_mapping", "identity_args_mapping"),
417
+ ):
418
+ if old in kwargs:
419
+ warnings.warn(
420
+ f"'{old}' was renamed to '{new}' in 0.8 and will be removed in 1.0."
421
+ " Update your code to use the new name.",
422
+ DeprecationWarning,
423
+ stacklevel=2,
424
+ )
425
+ old_value = kwargs.pop(old) # always remove old kwarg so it isn't forwarded
426
+ if new in kwargs:
427
+ # Both names present — common via dataclasses.replace() which auto-injects
428
+ # the current field value under the new name. Honour the old-name value
429
+ # (the caller's explicit intent) and discard the auto-injected value.
430
+ kwargs.pop(new)
431
+ kwargs[new] = old_value
432
+ _dwi_orig_init(self, *args, **kwargs) # type: ignore[arg-type]
433
+
434
+
435
+ DeprecationWrapperInfo.__init__ = _dwi_compat_init # type: ignore[method-assign]
436
+
437
+
438
+ def _getmembers_static_compat(obj: Any) -> list[tuple[str, Any]]: # noqa: ANN401
439
+ """Return members without triggering dynamic ``getattr`` side effects.
440
+
441
+ Uses ``inspect.getmembers_static`` when available (Python 3.11+). For Python
442
+ 3.9/3.10 compatibility, falls back to ``dir()`` + ``inspect.getattr_static``.
443
+
444
+ """
445
+ getmembers_static = getattr(inspect, "getmembers_static", None)
446
+ if callable(getmembers_static):
447
+ return getmembers_static(obj)
448
+
449
+ names = dir(obj)
450
+ members: list[tuple[str, Any]] = []
451
+ for name in names:
452
+ with suppress(AttributeError):
453
+ members.append((name, inspect.getattr_static(obj, name)))
454
+ return sorted(members, key=lambda item: item[0])
455
+
456
+
457
+ def _detect_chain_type(
458
+ dep_info: DeprecationConfig,
459
+ func: Callable,
460
+ target: Any, # noqa: ANN401
461
+ _is_args_remap: bool,
462
+ ) -> Optional[ChainType]:
463
+ """Return the chain type when target or attrs_mapping forms a deprecation chain, else None."""
464
+ chain_type: Optional[ChainType] = None
465
+ if callable(target) and _has_deprecation_meta(target):
466
+ wrp_depr_tgt = target.__deprecated__.target
467
+ chain_type = ChainType.STACKED if wrp_depr_tgt is TargetMode.ARGS_REMAP else ChainType.TARGET
468
+ elif _is_args_remap:
469
+ wrapped = getattr(func, "__wrapped__", None)
470
+ # ``target`` is always a ``TargetMode`` (or callable/None) after normalization — the legacy
471
+ # ``target is True`` sentinel can no longer reach here, so only ARGS_REMAP marks a stacked chain.
472
+ if (
473
+ wrapped is not None
474
+ and _has_deprecation_meta(wrapped)
475
+ and wrapped.__deprecated__.target is TargetMode.ARGS_REMAP
476
+ ):
477
+ chain_type = ChainType.STACKED
478
+ attrs_mapping = dep_info.attrs_mapping
479
+ has_chained_attrs = attrs_mapping is not None and any(
480
+ v is not None and v in attrs_mapping for v in attrs_mapping.values()
481
+ )
482
+ if chain_type is None and has_chained_attrs:
483
+ chain_type = ChainType.STACKED
484
+ return chain_type
485
+
486
+
487
+ def _validate_args_mapping(
488
+ func: Callable,
489
+ args_mapping: Optional[dict[str, Optional[str]]],
490
+ ) -> tuple[list[str], list[str], bool]:
491
+ """Return (invalid_args, identity_args_mapping, all_identity) for the given mapping."""
492
+ if not args_mapping:
493
+ return [], [], False
494
+ if isinstance(func, _DeprecatedProxy):
495
+ invalid_args: list[str] = []
496
+ else:
497
+ func_args = [arg[0] for arg in get_func_arguments_types_defaults(func)]
498
+ invalid_args = [arg for arg in args_mapping if arg not in func_args]
499
+ identity_args_mapping = [arg for arg, val in args_mapping.items() if arg == val]
500
+ all_identity = len(identity_args_mapping) == len(args_mapping) > 0
501
+ return invalid_args, identity_args_mapping, all_identity
502
+
503
+
504
+ def validate_deprecation_wrapper(func: Callable) -> DeprecationWrapperInfo:
505
+ """Validate if a deprecated wrapper configuration is effective.
506
+
507
+ This is a development tool to check if deprecated wrappers are configured correctly and will have the intended
508
+ effect. It examines the ``__deprecated__`` attribute set by the :func:`~deprecate.deprecated` decorator and
509
+ identifies
510
+ configurations that would result in zero impact:
511
+
512
+ - args_mapping keys that don't exist in the function's signature
513
+ - Empty or None args_mapping (no argument remapping)
514
+ - Identity mappings where key equals value (e.g., {'arg': 'arg'})
515
+ - Target pointing to the same function (self-reference)
516
+ - target=None with no args_mapping (just warns, no forwarding)
517
+
518
+ Args:
519
+ func: The decorated function to validate. Must have a ``__deprecated__`` attribute set by the ``@deprecated``
520
+ decorator.
521
+
522
+ Returns:
523
+ :class:`~deprecate.audit.DeprecationWrapperInfo`: Dataclass with validation results:
524
+ - function: Name of the wrapper being validated
525
+ - deprecated_info: The typed :class:`~deprecate._types.DeprecationConfig` metadata from ``__deprecated__``
526
+ - invalid_args: List of args_mapping keys not in wrapper signature
527
+ - empty_args_mapping: True if args_mapping is None or empty
528
+ - identity_args_mapping: List of args where key equals value (no effect)
529
+ - self_reference: True if target is the same as the wrapper
530
+ - no_effect: True if wrapper has zero impact (all checks combined)
531
+ - empty_deprecated_in: True when ``deprecated_in`` is absent or empty
532
+
533
+ Raises:
534
+ ValueError: If the wrapper has missing or invalid ``__deprecated__`` metadata (expected
535
+ :class:`~deprecate._types.DeprecationConfig`).
536
+
537
+ Example:
538
+ >>> from deprecate import TargetMode, deprecated, validate_deprecation_wrapper
539
+ >>> def new_implementation(value: int) -> int:
540
+ ... return value * 2
541
+ >>>
542
+ >>> @deprecated(target=new_implementation, deprecated_in="1.0", args_mapping={"old_val": "value"})
543
+ ... def old_func(old_val: int) -> int:
544
+ ... pass
545
+ >>>
546
+ >>> # Valid mapping to different function - has effect
547
+ >>> result = validate_deprecation_wrapper(old_func)
548
+ >>> result.no_effect
549
+ False
550
+ >>> result.invalid_args
551
+ []
552
+
553
+ >>> @deprecated(target=TargetMode.ARGS_REMAP, deprecated_in="1.0", args_mapping={"arg": "arg"})
554
+ ... def identity_func(arg: int) -> int:
555
+ ... return arg
556
+ >>>
557
+ >>> # Identity mapping with self-deprecation - no effect
558
+ >>> result = validate_deprecation_wrapper(identity_func)
559
+ >>> result.identity_args_mapping
560
+ ['arg']
561
+ >>> result.no_effect
562
+ True
563
+
564
+ Note:
565
+ Use this function during development or in CI to ensure deprecation decorators are configured meaningfully.
566
+ Invalid configurations won't cause runtime errors but will silently have no effect.
567
+
568
+ """
569
+ if not _has_deprecation_meta(func):
570
+ raise ValueError(
571
+ f"Function {getattr(func, '__name__', func)} has missing or invalid `__deprecated__` metadata. "
572
+ "Expected `DeprecationConfig`; ensure it is decorated with `@deprecated`."
573
+ )
574
+
575
+ dep_info = func.__deprecated__
576
+ args_mapping = dep_info.args_mapping
577
+ target = dep_info.target
578
+ _is_args_remap = target is TargetMode.ARGS_REMAP
579
+ _is_notify = target is TargetMode.NOTIFY
580
+
581
+ # Self-reference: the wrapper forwards to itself. For a proxy the wrapper object is the proxy while its
582
+ # deprecated target is the *wrapped* object, so ``target is func`` never matches — compare against
583
+ # ``func.wrapped`` too. A proxy is self-referential only when there is *no* active remapping:
584
+ # a proxy with non-empty ``args_mapping`` or ``attrs_mapping`` still performs meaningful transformation
585
+ # and must not be flagged as a no-op.
586
+ self_reference = target is not None and (
587
+ target is func
588
+ or (
589
+ isinstance(func, _DeprecatedProxy)
590
+ and target is func.wrapped
591
+ and not dep_info.args_mapping
592
+ and not dep_info.attrs_mapping
593
+ )
594
+ )
595
+ empty_args_mapping = not args_mapping
596
+ chain_type = _detect_chain_type(dep_info, func, target, _is_args_remap)
597
+ invalid_args, identity_args_mapping, all_identity = _validate_args_mapping(func, args_mapping)
598
+
599
+ # NOTIFY (target=None) is NOT no_effect — it still emits deprecation warnings.
600
+ # When target is a different function, there's ALWAYS an effect (forwarding).
601
+ is_self_deprecation = _is_args_remap or self_reference
602
+ no_effect = self_reference or (is_self_deprecation and (empty_args_mapping or all_identity))
603
+
604
+ # Construction-time `target=False` is captured in DeprecationConfig.misconfigured by the
605
+ # decorator/proxy before normalisation; NOTIFY ignores args_mapping; ARGS_REMAP needs args_mapping.
606
+ misconfigured_target = (
607
+ bool(getattr(dep_info, "misconfigured", False))
608
+ or (_is_notify and bool(args_mapping))
609
+ or (_is_args_remap and empty_args_mapping)
610
+ )
611
+
612
+ function = dep_info.name or getattr(func, "__name__", str(func))
613
+
614
+ return DeprecationWrapperInfo(
615
+ function=function,
616
+ deprecated_info=dep_info,
617
+ invalid_args=invalid_args,
618
+ empty_args_mapping=empty_args_mapping,
619
+ identity_args_mapping=identity_args_mapping,
620
+ self_reference=self_reference,
621
+ no_effect=no_effect,
622
+ misconfigured_target=misconfigured_target,
623
+ all_identity=all_identity,
624
+ chain_type=chain_type,
625
+ args_mapping_auto_expanded=list(getattr(dep_info, "args_mapping_auto_expanded", ())),
626
+ args_mapping_positional_only=list(getattr(dep_info, "args_mapping_positional_only", ())),
627
+ )
628
+
629
+
630
+ def _check_deprecated_wrapper_expiry(func: Callable, current_version: str) -> None:
631
+ """Check if a deprecated wrapper has passed its scheduled removal version.
632
+
633
+ This is an internal helper function used by :func:`~deprecate.audit.validate_deprecation_expiry`.
634
+ It verifies that deprecated code is actually removed when it reaches its scheduled removal deadline.
635
+
636
+ The function validates that the wrapper is properly decorated, extracts the removal version from its metadata,
637
+ and compares it against the current version using semantic versioning. If the current version is greater than or
638
+ equal to the scheduled removal version, it raises an AssertionError indicating the code must be deleted.
639
+
640
+ Args:
641
+ func: The deprecated callable to check. Must have a ``__deprecated__`` attribute set by the ``@deprecated``
642
+ decorator.
643
+ current_version: The current version of the package (e.g., "2.0.0"). Should follow PEP 440 versioning
644
+ conventions.
645
+
646
+ Raises:
647
+ ValueError: If the wrapper has missing or invalid ``__deprecated__`` metadata (expected
648
+ :class:`~deprecate._types.DeprecationConfig`).
649
+ ValueError: If the ``remove_in`` field is missing from the deprecation metadata.
650
+ AssertionError: If the current version is greater than or equal to the scheduled removal version, indicating
651
+ the code should have been removed.
652
+
653
+ """
654
+ # First validate that the wrapper has proper deprecation metadata
655
+ info = validate_deprecation_wrapper(func)
656
+
657
+ # Extract the remove_in version from the metadata
658
+ remove_in = info.deprecated_info.remove_in
659
+ if not remove_in:
660
+ raise ValueError(
661
+ f"Callable `{info.function}` does not have a 'remove_in' version specified in its deprecation metadata."
662
+ )
663
+
664
+ # Parse both versions for proper semantic version comparison
665
+ # Let ImportError propagate with its helpful install message
666
+ try:
667
+ current_ver = _parse_version(current_version)
668
+ except ValueError as err:
669
+ raise ValueError(f"Invalid current_version '{current_version}': {err}") from err
670
+
671
+ try:
672
+ remove_ver = _parse_version(remove_in)
673
+ except ValueError as err:
674
+ raise ValueError(f"Invalid remove_in '{remove_in}' for callable `{info.function}`: {err}") from err
675
+
676
+ # Check if the current version has reached or passed the removal deadline
677
+ if current_ver >= remove_ver:
678
+ raise AssertionError(
679
+ f"Callable `{info.function}` was scheduled for removal in version {remove_in} "
680
+ f"but still exists in version {current_version}. Please delete this deprecated code."
681
+ )
682
+
683
+
684
+ def _get_package_version(package_name: str) -> str:
685
+ """Auto-detect the installed version of a package.
686
+
687
+ This private helper function attempts to retrieve the version of an installed package using importlib.metadata,
688
+ with a fallback to checking the package's ``__version__`` attribute. This is useful for automatically detecting
689
+ the current version of a package when checking deprecation expiry.
690
+
691
+ Args:
692
+ package_name: Name of the package to get the version for (e.g., "numpy", "mypackage").
693
+
694
+ Returns:
695
+ The version string of the installed package.
696
+
697
+ Raises:
698
+ ImportError: If the package is not installed or version cannot be determined.
699
+
700
+ """
701
+ # Try importlib.metadata first (standard approach for installed packages)
702
+ with suppress(Exception):
703
+ return importlib.metadata.version(package_name)
704
+
705
+ # Fall back to checking __version__ attribute
706
+ with suppress(Exception):
707
+ module = importlib.import_module(package_name)
708
+ if hasattr(module, "__version__"):
709
+ return module.__version__
710
+
711
+ # If both methods fail, raise an informative error
712
+ raise ImportError(
713
+ f"Could not determine version for package '{package_name}'. "
714
+ f"Ensure the package is installed and has version metadata."
715
+ )
716
+
717
+
718
+ def _check_expiry_for_callables(results: list[DeprecationWrapperInfo], current_version: str) -> list[str]:
719
+ """Apply expiry comparison to pre-scanned wrapper results.
720
+
721
+ Shared implementation used by :func:`validate_deprecation_expiry` and the CLI's single-scan path. Keeps the
722
+ error message format in one place.
723
+
724
+ Args:
725
+ results: Pre-scanned wrapper info list.
726
+ current_version: Current package version string for comparison (PEP 440).
727
+
728
+ Returns:
729
+ List of expiry error messages for callables that have passed their removal deadline.
730
+
731
+ Raises:
732
+ ImportError: If the ``packaging`` library is not installed.
733
+
734
+ """
735
+ current_ver = _parse_version(current_version)
736
+ expired = []
737
+ for info in results:
738
+ remove_in = info.deprecated_info.remove_in
739
+ if not remove_in:
740
+ continue
741
+ try:
742
+ remove_ver = _parse_version(remove_in)
743
+ except ValueError:
744
+ # An unparsable ``remove_in`` (e.g. a typo) would make the wrapper permanently un-expirable and the
745
+ # batch gate would never flag it. Warn per skip so the misconfiguration is visible rather than silent
746
+ # — the single-callable path raises; here a warning keeps the batch scan going for the rest.
747
+ warnings.warn(
748
+ f"Callable `{info.function}` has an unparsable `remove_in` version `{remove_in}`; "
749
+ "its expiry cannot be checked until the version string is fixed.",
750
+ stacklevel=2,
751
+ )
752
+ continue
753
+ if current_ver >= remove_ver:
754
+ expired.append(
755
+ f"Callable `{info.function}` was scheduled for removal in version {remove_in}"
756
+ f" but still exists in version {current_version}. Please delete this deprecated code."
757
+ )
758
+ return expired
759
+
760
+
761
+ def validate_deprecation_expiry(
762
+ module: Union[Any, str], # noqa: ANN401
763
+ current_version: Optional[str] = None,
764
+ recursive: bool = True,
765
+ include_members: bool = True,
766
+ ) -> list[str]:
767
+ """Check all deprecated callables in a module/package for expired removal deadlines.
768
+
769
+ This enforcement tool scans an entire module or package for deprecated functions and checks if any have passed
770
+ their scheduled removal version. It's designed for CI/CD pipelines to automatically detect and report zombie code
771
+ across a codebase.
772
+
773
+ The function uses :func:`~deprecate.audit.find_deprecation_wrappers` to discover all deprecated wrappers,
774
+ then checks each one against
775
+ the current version. Any wrappers that have reached or passed their removal deadline are collected and reported.
776
+
777
+ Args:
778
+ module: A Python module or package to scan. Can be:
779
+ - Imported module object (e.g., ``import my_package; validate_deprecation_expiry(my_package, "2.0")``)
780
+ - String module path (e.g., ``validate_deprecation_expiry("my_package.submodule", "2.0")``)
781
+ current_version: The current version of your package to compare against removal deadlines (e.g., ``"2.0.0"``).
782
+ If None, attempts to auto-detect the version using the package name from the module path (e.g.,
783
+ ``"mypackage"`` extracts ``mypackage`` as package name).
784
+ recursive: If True (default), recursively scan submodules. If False, only scan the top-level module.
785
+ include_members: If True (default), also scan deprecated class members (methods, constructors,
786
+ classmethods, staticmethods, properties) — matching the discovery default of
787
+ :func:`~deprecate.audit.find_deprecation_wrappers`, so the enforcement gate sees everything
788
+ discovery and reporting see.
789
+
790
+ Returns:
791
+ List of error messages for callables that have expired (past their removal deadline).
792
+ Empty list if all deprecated callables are still within their deprecation period.
793
+
794
+ Example:
795
+ >>> # Check a specific module with version before any deadlines
796
+ >>> from deprecate import validate_deprecation_expiry
797
+ >>> expired = validate_deprecation_expiry("tests.collection_deprecate", "0.1", recursive=False)
798
+ >>> len(expired)
799
+ 0
800
+
801
+ >>> # Check with version past some removal deadlines
802
+ >>> expired = validate_deprecation_expiry("tests.collection_deprecate", "0.5", recursive=False)
803
+ >>> print(len(expired)) # Some functions and class members have remove_in <= "0.5"
804
+ 31
805
+
806
+ !!! note
807
+ - Skips callables without a ``remove_in`` field (warnings only, no removal deadline)
808
+ - Skips callables that cannot be imported or accessed
809
+ - Emits a ``UserWarning`` (rather than silently skipping) for callables with an unparsable ``remove_in``
810
+ - Uses semantic versioning comparison (e.g., "1.2.3" vs "2.0.0")
811
+ - Intended for automated checks in CI/CD pipelines
812
+ - Can be integrated into test suites or pre-commit hooks
813
+
814
+ """
815
+ # Determine module name for auto-version detection
816
+ module_name = module if isinstance(module, str) else getattr(module, "__name__", None)
817
+
818
+ # Auto-detect version if not provided
819
+ if current_version is None:
820
+ if not module_name:
821
+ raise ValueError(
822
+ "Cannot auto-detect version: module object has no __name__ attribute. "
823
+ "Please provide current_version explicitly."
824
+ )
825
+ # Extract package name (first component of module path)
826
+ package_name = module_name.split(".")[0]
827
+ current_version = _get_package_version(package_name)
828
+
829
+ # Validate current_version upfront for fail-fast feedback before the module scan.
830
+ try:
831
+ _parse_version(current_version)
832
+ except ValueError as err:
833
+ raise ValueError(f"Invalid current_version '{current_version}': {err}") from err
834
+
835
+ # Handle string module path
836
+ if isinstance(module, str):
837
+ module = importlib.import_module(module)
838
+
839
+ return _check_expiry_for_callables(
840
+ find_deprecation_wrappers(module, recursive=recursive, include_members=include_members), current_version
841
+ )
842
+
843
+
844
+ def _scan_callable(
845
+ obj: Any, # noqa: ANN401
846
+ module_name: str,
847
+ qualified_name: str,
848
+ *,
849
+ member_name: Optional[str] = None,
850
+ descriptor_kind: Optional[str] = None,
851
+ ) -> Optional[DeprecationWrapperInfo]:
852
+ """Emit a result if ``obj`` carries ``__deprecated__`` metadata."""
853
+ if _has_deprecation_meta(obj):
854
+ info = validate_deprecation_wrapper(obj)
855
+ api_type = _classify_wrapper_api_type(obj, info, member_name=member_name, descriptor_kind=descriptor_kind)
856
+ return replace(info, module=module_name, function=qualified_name, api_type=api_type)
857
+ return None
858
+
859
+
860
+ def _descriptor_underlying_callables(obj: Any) -> tuple[Any, ...]: # noqa: ANN401
861
+ """Return the underlying callable(s) from a descriptor, or a 1-tuple of *obj* for plain callables.
862
+
863
+ Centralises the descriptor-unwrapping logic shared by :func:`_member_has_deprecation_meta` and
864
+ :func:`_scan_class` so each descriptor type is handled in exactly one place.
865
+
866
+ Args:
867
+ obj: A raw class member — may be a ``classmethod``, ``staticmethod``, ``property``,
868
+ ``cached_property``, or a plain callable.
869
+
870
+ Returns:
871
+ A tuple of the underlying callable objects. Empty when ``obj`` is a ``cached_property``
872
+ with no ``func`` attribute (degenerate case).
873
+
874
+ Examples:
875
+ >>> import warnings
876
+ >>> _descriptor_underlying_callables(classmethod(warnings.warn)) # doctest: +ELLIPSIS
877
+ (<built-in function warn>,)
878
+ >>> _descriptor_underlying_callables(staticmethod(warnings.warn))
879
+ (<built-in function warn>,)
880
+
881
+ """
882
+ if isinstance(obj, (classmethod, staticmethod)):
883
+ return (obj.__func__,)
884
+ if isinstance(obj, property):
885
+ return tuple(a for a in (obj.fget, obj.fset, obj.fdel) if a is not None)
886
+ if isinstance(obj, cached_property):
887
+ func = getattr(obj, "func", None)
888
+ return (func,) if func is not None else ()
889
+ return (obj,)
890
+
891
+
892
+ def _member_has_deprecation_meta(obj: Any) -> bool: # noqa: ANN401
893
+ """Return ``True`` if a class member — peeking through descriptors — carries ``__deprecated__`` metadata.
894
+
895
+ Descriptors store the deprecation metadata on the underlying callable (``classmethod``/``staticmethod``
896
+ ``__func__``, ``property`` accessors, ``cached_property`` ``func``), so a plain :func:`_has_deprecation_meta`
897
+ on the raw member would miss deprecated descriptors.
898
+
899
+ Args:
900
+ obj: The raw class member (possibly a descriptor) to inspect.
901
+
902
+ """
903
+ return any(_has_deprecation_meta(c) for c in _descriptor_underlying_callables(obj))
904
+
905
+
906
+ def _scan_class(cls: Any, module_name: str, cls_name: str) -> list[DeprecationWrapperInfo]: # noqa: ANN401
907
+ """Scan class members, peeking through descriptors."""
908
+ results: list[DeprecationWrapperInfo] = []
909
+ try:
910
+ members = _getmembers_static_compat(cls)
911
+ except (AttributeError, TypeError):
912
+ return results
913
+ for attr_name, obj in members:
914
+ # Skip private/dunder members that are *not* themselves deprecated. Deprecated private or dunder
915
+ # members (e.g. a deprecated ``_legacy`` method or ``__eq__``) still carry ``__deprecated__`` and must
916
+ # be surfaced so they can expire — only ``__init__`` is exempt.
917
+ if attr_name.startswith("_") and attr_name != "__init__" and not _member_has_deprecation_meta(obj):
918
+ continue
919
+ qualified = f"{cls_name}.{attr_name}"
920
+ result: Optional[DeprecationWrapperInfo] = None
921
+ if isinstance(obj, (classmethod, staticmethod)):
922
+ kind = "classmethod" if isinstance(obj, classmethod) else "staticmethod"
923
+ result = _scan_callable(obj.__func__, module_name, qualified, member_name=attr_name, descriptor_kind=kind)
924
+ elif isinstance(obj, property):
925
+ _prop_accessor = next(
926
+ (c for c in _descriptor_underlying_callables(obj) if _has_deprecation_meta(c)),
927
+ None,
928
+ )
929
+ if _prop_accessor is not None:
930
+ result = _scan_callable(_prop_accessor, module_name, qualified, member_name=attr_name)
931
+ # Inner-order ``@property @deprecated``: a *plain* ``property`` (not ``_DeprecatedProperty``)
932
+ # whose ``fget`` is deprecation-wrapped. Only ``fget`` warns; any setter/deleter rebound
933
+ # afterwards is built from the plain ``property`` base and stays silent. Flag every such
934
+ # wrapper (getter-only included) since the canonical form is outer ``@deprecated(...) @property``.
935
+ if (
936
+ result is not None
937
+ and not isinstance(obj, _DeprecatedProperty)
938
+ and obj.fget is not None
939
+ and _has_deprecation_meta(obj.fget)
940
+ ):
941
+ result = replace(result, inner_order_property=True)
942
+ elif isinstance(obj, cached_property):
943
+ result = _scan_callable(obj.func, module_name, qualified, member_name=attr_name)
944
+ else:
945
+ result = _scan_callable(obj, module_name, qualified, member_name=attr_name)
946
+ if result is not None:
947
+ results.append(result)
948
+ return results
949
+
950
+
951
+ def _reexport_module(obj: Any) -> Optional[str]: # noqa: ANN401
952
+ """Return the defining module of a non-proxy deprecated wrapper, for re-export attribution.
953
+
954
+ ``functools.wraps`` preserves ``__module__`` on ``@deprecated`` functions, so a wrapper re-exported through another
955
+ package's ``__init__`` still reports the module it was defined in and can be attributed there rather than counted
956
+ once per importing module.
957
+
958
+ Proxies (:class:`~deprecate.proxy._DeprecatedProxy`) have no reliable defining module — normal lookup returns the
959
+ proxy class's own ``__module__`` and the wrapped object commonly lives in a different module than where the proxy
960
+ was created — so this returns ``None`` for them and the caller falls back to id-based dedup.
961
+
962
+ """
963
+ if isinstance(obj, _DeprecatedProxy):
964
+ return None
965
+ return getattr(obj, "__module__", None)
966
+
967
+
968
+ def _same_top_package(mod_a: str, mod_b: str) -> bool:
969
+ """Return True when ``mod_a`` and ``mod_b`` share the same top-level package."""
970
+ return mod_a.split(".")[0] == mod_b.split(".")[0]
971
+
972
+
973
+ def _scan_module(
974
+ mod: Any, # noqa: ANN401
975
+ *,
976
+ include_members: bool,
977
+ seen: set[int],
978
+ attribute_to_defining_module: bool = True,
979
+ ) -> list[DeprecationWrapperInfo]:
980
+ """Scan a single module for deprecated functions and class members.
981
+
982
+ ``seen`` accumulates ``id()`` of every wrapper already recorded across the whole :func:`find_deprecation_wrappers`
983
+ run so a re-exported wrapper (the same object bound in more than one module) is reported once, not once per
984
+ importing module.
985
+
986
+ When ``attribute_to_defining_module`` is True (the default), wrappers whose ``__module__`` differs from ``mod_name``
987
+ but belongs to the same top-level package are skipped — they will be counted when the recursive walk reaches their
988
+ defining submodule. Pass False when the defining submodule will not be visited (package scanned with
989
+ ``recursive=False``) so that re-exports visible on the public surface are not silently dropped.
990
+
991
+ """
992
+ results: list[DeprecationWrapperInfo] = []
993
+ try:
994
+ members = _getmembers_static_compat(mod)
995
+ except (AttributeError, TypeError, ImportError):
996
+ return results
997
+
998
+ mod_name = mod.__name__ if hasattr(mod, "__name__") else str(mod)
999
+ for name, obj in members:
1000
+ if name.startswith("_"):
1001
+ continue
1002
+
1003
+ if _has_deprecation_meta(obj):
1004
+ # Attribute a re-exported wrapper to its defining module, not to every module that
1005
+ # merely re-exports it. Non-proxy wrappers carry a reliable ``__module__``; proxies do
1006
+ # not, so they fall through to the id-based dedup below.
1007
+ # Guard 1 — only apply when a recursive walk will visit the defining module.
1008
+ # Guard 2 — only skip when the defining module is in the same top-level package;
1009
+ # if ``__module__`` points to an external package (e.g. a ``functools.partial``
1010
+ # wrapper whose ``__module__`` was not propagated by ``functools.wraps``), the
1011
+ # defining module will never be visited and the wrapper would be dropped silently.
1012
+ defining_module = _reexport_module(obj)
1013
+ if (
1014
+ attribute_to_defining_module
1015
+ and defining_module is not None
1016
+ and defining_module != mod_name
1017
+ and _same_top_package(defining_module, mod_name)
1018
+ ):
1019
+ continue
1020
+ if id(obj) in seen:
1021
+ continue
1022
+ seen.add(id(obj))
1023
+ result = _scan_callable(obj, mod_name, name)
1024
+ if result is not None:
1025
+ results.append(result)
1026
+ elif include_members and inspect.isclass(obj) and getattr(obj, "__module__", None) == mod_name:
1027
+ results.extend(_scan_class(obj, mod_name, name))
1028
+ return results
1029
+
1030
+
1031
+ def find_deprecation_wrappers(
1032
+ module: Union[Any, str], # noqa: ANN401
1033
+ recursive: bool = True,
1034
+ include_members: bool = True,
1035
+ ) -> list[DeprecationWrapperInfo]:
1036
+ """Scan a module or package for deprecated wrappers and validate them.
1037
+
1038
+ This is a development/CI tool to scan a codebase for all wrappers created with :func:`~deprecate.deprecated`,
1039
+ :func:`~deprecate.deprecated_class`, or :func:`~deprecate.deprecated_instance` and validate that each wrapper
1040
+ configuration is meaningful.
1041
+ Returns comprehensive information about each deprecated wrapper including validation results that help identify
1042
+ misconfigured wrappers.
1043
+
1044
+ Args:
1045
+ module: A Python module or package to scan for deprecated wrappers. Can be:
1046
+ - Imported module object (e.g., ``import my_package; find_deprecation_wrappers(my_package)``)
1047
+ - String module path (e.g., ``find_deprecation_wrappers("my_package.submodule")``)
1048
+ recursive: If True (default), recursively scan submodules. If False, only scan the top-level module.
1049
+ include_members: If True, also scan deprecated methods and constructors defined on classes.
1050
+
1051
+ Returns:
1052
+ List of :class:`~deprecate.audit.DeprecationWrapperInfo` dataclasses, one per deprecated wrapper found.
1053
+ Each contains:
1054
+ - module: Module name where the wrapper is defined
1055
+ - function: Wrapper name
1056
+ - deprecated_info: DeprecationConfig metadata from the decorator (``__deprecated__`` attribute)
1057
+ - invalid_args: List of args_mapping keys not in wrapper signature
1058
+ - empty_args_mapping: True if args_mapping is None or empty
1059
+ - identity_args_mapping: List of identity mappings (key == value)
1060
+ - self_reference: True if target points to same wrapper
1061
+ - no_effect: True if wrapper has zero impact
1062
+
1063
+ Example:
1064
+ >>> from deprecate import find_deprecation_wrappers
1065
+ >>> from tests import collection_deprecate as my_package
1066
+ >>>
1067
+ >>> results = find_deprecation_wrappers(my_package)
1068
+ >>> print(len(results) > 0) # Should find deprecated wrappers
1069
+ True
1070
+ >>> # Also works with string module paths
1071
+ >>> results = find_deprecation_wrappers("tests.collection_deprecate")
1072
+ >>> print(len(results) > 0)
1073
+ True
1074
+
1075
+ >>> # Filter to find only problematic wrappers
1076
+ >>> problematic = [r for r in results if r.invalid_args or r.no_effect]
1077
+ >>> print(len(results) > 0) # May or may not have problematic ones
1078
+ True
1079
+
1080
+ Note:
1081
+ - Requires that the module be importable
1082
+ - Recursive scans import every submodule of the package, executing their module-level code; packages
1083
+ with heavy import-time work (GPU init, network access) make the scan correspondingly expensive
1084
+ - Skips submodules that fail to import — any exception raised by module-level code is reported as a
1085
+ ``UserWarning`` (``audit: skipped <module>: ...``) and the scan continues
1086
+ - Inspects the ``__deprecated__`` attribute set by the :func:`~deprecate.deprecated` decorator
1087
+ - Skips private/magic attributes and imports from other modules
1088
+ - Uses static member inspection to avoid scan-time side effects from dynamic attribute access
1089
+
1090
+ """
1091
+ results: list[DeprecationWrapperInfo] = []
1092
+ # Track object identity across the whole scan so a wrapper re-exported through several modules
1093
+ # (the standard packaging pattern) is recorded once, not once per importing module.
1094
+ seen: set[int] = set()
1095
+
1096
+ # Handle string module path
1097
+ if isinstance(module, str):
1098
+ module = importlib.import_module(module)
1099
+
1100
+ # Disable the attribution filter only when the top module is a package AND recursive=False.
1101
+ # In that case the submodules that own the re-exported wrappers will never be visited, so
1102
+ # skipping re-exports would silently drop them. For single-file modules or recursive package
1103
+ # scans the old behaviour (attribute re-exports to their defining submodule) is preserved.
1104
+ _is_package = hasattr(module, "__path__")
1105
+ results.extend(
1106
+ _scan_module(
1107
+ module,
1108
+ include_members=include_members,
1109
+ seen=seen,
1110
+ attribute_to_defining_module=not (_is_package and not recursive),
1111
+ )
1112
+ )
1113
+
1114
+ if recursive and _is_package:
1115
+ try:
1116
+ packages = list(
1117
+ pkgutil.walk_packages(path=module.__path__, prefix=module.__name__ + ".", onerror=lambda x: None)
1118
+ )
1119
+ except (OSError, ImportError):
1120
+ packages = []
1121
+
1122
+ for _importer, modname, _ispkg in packages:
1123
+ # Submodule top-level code can raise anything at import time (RuntimeError, OSError, KeyError from
1124
+ # env lookups, ...), not just ImportError. One broken submodule must not abort the whole scan — and
1125
+ # with it every audit gate built on top — so catch broad Exception, keep the signal via a warning,
1126
+ # and continue with the remaining submodules.
1127
+ try:
1128
+ submod = importlib.import_module(modname)
1129
+ except Exception as exc:
1130
+ warnings.warn(f"audit: skipped {modname}: {exc!r}", stacklevel=2)
1131
+ continue
1132
+ results.extend(_scan_module(submod, include_members=include_members, seen=seen))
1133
+
1134
+ return results
1135
+
1136
+
1137
+ def _resolve_table_version(
1138
+ module: Union[Any, str], # noqa: ANN401
1139
+ *,
1140
+ current_version: Optional[str],
1141
+ ) -> tuple[Optional[str], Optional["Version"]]:
1142
+ """Resolve report version string and optional parsed version object."""
1143
+ module_name = module if isinstance(module, str) else getattr(module, "__name__", None)
1144
+ resolved_version = current_version
1145
+
1146
+ if resolved_version is None and module_name:
1147
+ with suppress(ImportError):
1148
+ resolved_version = _get_package_version(module_name.split(".")[0])
1149
+
1150
+ if resolved_version is None:
1151
+ return None, None
1152
+
1153
+ try:
1154
+ return resolved_version, _parse_version(resolved_version)
1155
+ except ImportError:
1156
+ return resolved_version, None
1157
+ except ValueError as err:
1158
+ if current_version is not None:
1159
+ raise ValueError(f"Invalid current_version '{current_version}': {err}") from err
1160
+ return resolved_version, None
1161
+
1162
+
1163
+ def _safe_parse_version(version: str) -> Optional["Version"]:
1164
+ """Best-effort version parser for report status evaluation."""
1165
+ if not version:
1166
+ return None
1167
+ try:
1168
+ return _parse_version(version)
1169
+ except (ImportError, ValueError):
1170
+ return None
1171
+
1172
+
1173
+ def _format_report_symbol(info: DeprecationWrapperInfo) -> str:
1174
+ """Return a stable fully-qualified label for report rows."""
1175
+ return f"{info.module}.{info.function}" if info.module else info.function
1176
+
1177
+
1178
+ def _format_report_target(target: Any) -> str: # noqa: ANN401
1179
+ """Format replacement target name for report rows."""
1180
+ if target is None or target is TargetMode.NOTIFY:
1181
+ return "—"
1182
+ if isinstance(target, TargetMode):
1183
+ return target.value
1184
+ if isinstance(target, _DeprecatedProxy):
1185
+ # A chained-proxy target (the New API is itself a deprecated alias). Bypass proxy
1186
+ # ``__getattr__`` interception to read the static metadata directly — ``__deprecated__``
1187
+ # is stored in the instance ``__dict__`` via ``object.__setattr__`` in ``_DeprecatedProxy.__init__``,
1188
+ # so ``object.__getattribute__`` retrieves it without triggering forwarding logic.
1189
+ return object.__getattribute__(target, "__deprecated__").name
1190
+ if callable(target):
1191
+ target_module = getattr(target, "__module__", "")
1192
+ target_name = getattr(target, "__qualname__", getattr(target, "__name__", str(target)))
1193
+ return f"{target_module}.{target_name}" if target_module else target_name
1194
+ return str(target)
1195
+
1196
+
1197
+ def _classify_member_api_type(member_name: str, descriptor_kind: Optional[str], has_mapping: bool) -> str:
1198
+ """Classify the API type for a deprecated class member (method, constructor, descriptor)."""
1199
+ if member_name == "__init__":
1200
+ return "class constructor args" if has_mapping else "class constructor"
1201
+ if descriptor_kind == "classmethod":
1202
+ return "classmethod args" if has_mapping else "classmethod"
1203
+ if descriptor_kind == "staticmethod":
1204
+ return "staticmethod args" if has_mapping else "staticmethod"
1205
+ return "class method args" if has_mapping else "class method"
1206
+
1207
+
1208
+ def _classify_wrapper_api_type(
1209
+ wrapped_obj: Any, # noqa: ANN401
1210
+ info: DeprecationWrapperInfo,
1211
+ *,
1212
+ member_name: Optional[str] = None,
1213
+ descriptor_kind: Optional[str] = None,
1214
+ ) -> str:
1215
+ """Classify wrapper kind for markdown report rows."""
1216
+ has_mapping = bool(info.deprecated_info.args_mapping)
1217
+
1218
+ if member_name is not None:
1219
+ return _classify_member_api_type(member_name, descriptor_kind, has_mapping)
1220
+
1221
+ if isinstance(wrapped_obj, _DeprecatedProxy):
1222
+ while isinstance(wrapped_obj, _DeprecatedProxy):
1223
+ wrapped_obj = wrapped_obj.wrapped
1224
+ if inspect.isclass(wrapped_obj):
1225
+ if is_dataclass(wrapped_obj):
1226
+ return "dataclass attributes" if has_mapping else "dataclass"
1227
+ return "class"
1228
+ return "data"
1229
+
1230
+ if inspect.isclass(wrapped_obj):
1231
+ if is_dataclass(wrapped_obj):
1232
+ return "dataclass attributes" if has_mapping else "dataclass"
1233
+ return "class"
1234
+
1235
+ if has_mapping:
1236
+ return "args"
1237
+
1238
+ return "callable"
1239
+
1240
+
1241
+ def _format_report_api_type(info: DeprecationWrapperInfo) -> str:
1242
+ """Return api_type with backward-compatible fallback."""
1243
+ if info.api_type:
1244
+ return info.api_type
1245
+ return "args" if info.deprecated_info.args_mapping else "callable"
1246
+
1247
+
1248
+ def _report_row_sort_key(info: DeprecationWrapperInfo) -> tuple[str, str, str, bool, str]:
1249
+ """Sort report rows by module and symbol family, keeping args-variants adjacent."""
1250
+ function = info.function or ""
1251
+ top_level = function.split(".", maxsplit=1)[0] if function else ""
1252
+ api_type = _format_report_api_type(info)
1253
+ return (info.module or "", top_level, function, api_type.endswith(" args"), api_type)
1254
+
1255
+
1256
+ def _format_version(version: Optional[str], *, missing: str = "—") -> str:
1257
+ """Format version values with a stable ``v`` prefix for report output."""
1258
+ if not version:
1259
+ return missing
1260
+ # Strip a single left-anchored leading ``v``/``V`` (``lstrip`` would remove *all* leading v's).
1261
+ return f"v{re.sub(r'^[vV]', '', version)}"
1262
+
1263
+
1264
+ def _get_deprecation_status(info: DeprecationWrapperInfo, current_version: Optional["Version"]) -> DeprecationStatus:
1265
+ """Classify one deprecated symbol into a report lifecycle status."""
1266
+ if current_version is None:
1267
+ return (
1268
+ DeprecationStatus.NO_REMOVAL_TARGET
1269
+ if not info.deprecated_info.remove_in
1270
+ else DeprecationStatus.STATUS_UNKNOWN
1271
+ )
1272
+
1273
+ deprecated_in = _safe_parse_version(info.deprecated_info.deprecated_in)
1274
+ if deprecated_in is not None and current_version < deprecated_in:
1275
+ return DeprecationStatus.SCHEDULED_DEPRECATION
1276
+
1277
+ remove_in = info.deprecated_info.remove_in
1278
+ if not remove_in:
1279
+ return DeprecationStatus.NO_REMOVAL_TARGET
1280
+
1281
+ remove_version = _safe_parse_version(remove_in)
1282
+ if remove_version is None:
1283
+ return DeprecationStatus.INVALID_REMOVAL_TARGET
1284
+
1285
+ if current_version >= remove_version:
1286
+ return DeprecationStatus.PAST_REMOVAL_DATE
1287
+
1288
+ # Pre-release of the same base release as remove_in gets an elevated status:
1289
+ # dev/alpha/beta → REMOVAL_IMMINENT; rc → REMOVE_BEFORE_RELEASE.
1290
+ # base_version strips pre/post/dev/local markers so "1.8" == "1.8.0" compare equal.
1291
+ if current_version.is_prerelease:
1292
+ try:
1293
+ _VersionType = type(current_version) # noqa: N806
1294
+ same_base = _VersionType(current_version.base_version) == _VersionType(remove_version.base_version)
1295
+ except Exception:
1296
+ same_base = False
1297
+ if same_base:
1298
+ if current_version.pre is not None and current_version.pre[0] == "rc":
1299
+ return DeprecationStatus.REMOVE_BEFORE_RELEASE
1300
+ return DeprecationStatus.REMOVAL_IMMINENT
1301
+
1302
+ return DeprecationStatus.ACTIVE_WARNING
1303
+
1304
+
1305
+ def _format_matrix_row(info: DeprecationWrapperInfo, col_idx: dict[str, int], n_versions: int) -> str:
1306
+ """Format one matrix-style table row for a deprecated wrapper."""
1307
+ markers: list[str] = [" "] * n_versions
1308
+ dep_in = info.deprecated_info.deprecated_in
1309
+ rem_in = info.deprecated_info.remove_in
1310
+ if dep_in and dep_in in col_idx:
1311
+ markers[col_idx[dep_in]] = "D"
1312
+ if rem_in and rem_in in col_idx:
1313
+ i = col_idx[rem_in]
1314
+ markers[i] = "R" if markers[i] == " " else "D/R"
1315
+ return (
1316
+ "| "
1317
+ f"`{_format_report_symbol(info)}` | "
1318
+ f"{_format_report_api_type(info)} | "
1319
+ f"`{_format_report_target(info.deprecated_info.target)}` | " + " | ".join(markers) + " |"
1320
+ )
1321
+
1322
+
1323
+ def generate_deprecation_table(
1324
+ module: Union[Any, str], # noqa: ANN401
1325
+ current_version: Optional[str] = None,
1326
+ recursive: bool = True,
1327
+ style: Union[TableStyle, str] = TableStyle.COMPACT,
1328
+ include_members: bool = True,
1329
+ *,
1330
+ _wrappers: Optional[list["DeprecationWrapperInfo"]] = None,
1331
+ ) -> str:
1332
+ """Generate a markdown table summarizing deprecated wrappers.
1333
+
1334
+ The table is derived from ``__deprecated__`` metadata and includes both
1335
+ top-level wrappers and deprecated class members (methods/constructors).
1336
+
1337
+ Args:
1338
+ module: Imported module/package object or string module path to scan.
1339
+ current_version: Optional current package version for lifecycle status
1340
+ evaluation in compact style. If ``None``, auto-detection is attempted
1341
+ via the package name; status falls back to ``"⚪ Status Unknown"`` when
1342
+ ``packaging`` is not installed.
1343
+ recursive: If True (default), include submodules in the scan.
1344
+ style: Table format — ``"compact"`` or ``"matrix"``.
1345
+ - ``"compact"``: ``Original API | API Type | New API | Deprecated | Remove | Current Status``
1346
+ - ``"matrix"``: ``Original API | API Type | New API | <all versions...>``, with markers
1347
+ ``D`` (deprecated) and ``R`` (remove) in version columns.
1348
+ include_members: If True (default), include deprecated class members (methods, constructors).
1349
+
1350
+ Returns:
1351
+ Markdown string containing a formatted table. When a version is
1352
+ resolvable (either from current_version or auto-detected), the
1353
+ first line is an HTML comment <!-- Current version: X.Y -->
1354
+ followed by the header row and alignment row. When no version can be
1355
+ resolved, the first line is the header row directly.
1356
+
1357
+ Raises:
1358
+ ValueError: If ``style`` is not ``"compact"`` or ``"matrix"``, or if
1359
+ ``current_version`` is supplied but is not a valid PEP 440 version
1360
+ string and ``packaging`` is installed.
1361
+
1362
+ Example:
1363
+ >>> from tests import collection_deprecate as pkg
1364
+ >>> report = generate_deprecation_table(pkg, recursive=False)
1365
+ >>> report.splitlines()[0]
1366
+ '| Original API | API Type | New API | Deprecated | Remove | Current Status |'
1367
+
1368
+ """
1369
+ try:
1370
+ style = TableStyle(style)
1371
+ except ValueError as err:
1372
+ raise ValueError(
1373
+ f"Invalid style {style!r}. Expected one of: {', '.join(s.value for s in TableStyle)}."
1374
+ ) from err
1375
+
1376
+ resolved_version, parsed_version = _resolve_table_version(module, current_version=current_version)
1377
+ if _wrappers is None:
1378
+ _wrappers = find_deprecation_wrappers(module, recursive=recursive, include_members=include_members)
1379
+ wrappers = sorted(
1380
+ _wrappers,
1381
+ key=_report_row_sort_key,
1382
+ )
1383
+
1384
+ if style == TableStyle.COMPACT:
1385
+ rows = [
1386
+ "| Original API | API Type | New API | Deprecated | Remove | Current Status |",
1387
+ "| :--- | :--- | :--- | :---: | :---: | :--- |",
1388
+ ]
1389
+
1390
+ for info in wrappers:
1391
+ rows.append(
1392
+ "| "
1393
+ f"`{_format_report_symbol(info)}` | "
1394
+ f"{_format_report_api_type(info)} | "
1395
+ f"`{_format_report_target(info.deprecated_info.target)}` | "
1396
+ f"{_format_version(info.deprecated_info.deprecated_in)} | "
1397
+ f"{_format_version(info.deprecated_info.remove_in)} | "
1398
+ f"{_get_deprecation_status(info, parsed_version).value} |"
1399
+ )
1400
+ else:
1401
+ version_map: dict[str, Optional[Version]] = {}
1402
+ for info in wrappers:
1403
+ for version in (info.deprecated_info.deprecated_in, info.deprecated_info.remove_in):
1404
+ if version and version not in version_map:
1405
+ version_map[version] = _safe_parse_version(version)
1406
+
1407
+ sorted_versions = sorted(
1408
+ version_map,
1409
+ key=lambda version: (
1410
+ version_map[version] is None,
1411
+ version_map[version] if version_map[version] is not None else version,
1412
+ ),
1413
+ )
1414
+ version_headers = [_format_version(version) for version in sorted_versions]
1415
+ header_row = "| Original API | API Type | New API | " + " | ".join(version_headers) + " |"
1416
+ divider_row = "| :--- | :--- | :--- | " + " | ".join(":---:" for _ in version_headers) + " |"
1417
+ col_idx = {v: i for i, v in enumerate(sorted_versions)}
1418
+ n_versions = len(sorted_versions)
1419
+ rows = [header_row, divider_row]
1420
+
1421
+ for info in wrappers:
1422
+ rows.append(_format_matrix_row(info, col_idx, n_versions))
1423
+
1424
+ if resolved_version is not None:
1425
+ rows.insert(0, f"<!-- Current version: {resolved_version} -->")
1426
+
1427
+ return "\n".join(rows)
1428
+
1429
+
1430
+ def validate_deprecation_chains(
1431
+ module: Union[Any, str], # noqa: ANN401
1432
+ recursive: bool = True,
1433
+ ) -> list[DeprecationWrapperInfo]:
1434
+ """Validate that deprecated functions don't form chains with other deprecated code.
1435
+
1436
+ This is a developer utility that scans a module or package for deprecated functions that form chains in two ways:
1437
+
1438
+ 1. **TARGET chains**: The ``target`` argument points to another deprecated callable instead of the final
1439
+ non-deprecated implementation.
1440
+ 2. **STACKED chains**: Multiple ``@deprecated(target=TargetMode.ARGS_REMAP, ...)`` decorators are stacked on the
1441
+ same function with argument mappings that should be collapsed, or a callable ``target`` is itself a
1442
+ self-deprecation (``target=TargetMode.ARGS_REMAP``) requiring mapping composition.
1443
+
1444
+ Both types are wasteful: wrappers should point directly to the final (non-deprecated) implementation with
1445
+ composed argument mappings.
1446
+
1447
+ Detection is based purely on decorator metadata (``__deprecated__`` attributes) — no source-code or AST
1448
+ inspection is performed.
1449
+
1450
+ Args:
1451
+ module: A Python module or package to scan for deprecation chains. Can be:
1452
+ - Imported module object (e.g., ``import my_package; validate_deprecation_chains(my_package)``)
1453
+ - String module path (e.g., ``validate_deprecation_chains("my_package.submodule")``)
1454
+ recursive: If True (default), recursively scan submodules. If False, only scan the top-level module.
1455
+
1456
+ Returns:
1457
+ List of :class:`~deprecate.audit.DeprecationWrapperInfo` where ``chain_type`` is not ``None``, i.e. every
1458
+ deprecated wrapper that forms a chain (``ChainType.TARGET`` or ``ChainType.STACKED``).
1459
+
1460
+ Example:
1461
+ >>> from deprecate import validate_deprecation_chains
1462
+ >>> import tests.collection_chains as test_module
1463
+ >>>
1464
+ >>> issues = validate_deprecation_chains(test_module, recursive=False)
1465
+ >>> len(issues) > 0 # Should find chains
1466
+ True
1467
+
1468
+ Note:
1469
+ - Only flags callees using the :func:`~deprecate.deprecated` decorator
1470
+ - Uses :func:`~deprecate.audit.find_deprecation_wrappers` and inspects ``chain_type`` to detect chains
1471
+
1472
+ """
1473
+ return [info for info in find_deprecation_wrappers(module, recursive=recursive) if info.chain_type is not None]
1474
+
1475
+
1476
+ def validate_mapping_compatibility(
1477
+ module: Union[Any, str], # noqa: ANN401
1478
+ recursive: bool = True,
1479
+ ) -> list[DeprecationWrapperInfo]:
1480
+ """Return wrappers whose ``args_mapping`` remaps deprecated names to POSITIONAL_ONLY constructor params.
1481
+
1482
+ A non-empty ``args_mapping_positional_only`` on the returned ``DeprecationWrapperInfo`` means the
1483
+ proxy falls back to ``setattr`` at call time instead of forwarding the remapped kwarg. Use this
1484
+ validator in CI to detect :func:`~deprecate.proxy.deprecated_class` configurations that silently
1485
+ degrade to attribute assignment and may not behave as expected on all target class types.
1486
+
1487
+ Args:
1488
+ module: A Python module or package to scan. Accepts an imported module object or a dotted
1489
+ module path string.
1490
+ recursive: When ``True`` (default) recursively scan submodules.
1491
+
1492
+ Returns:
1493
+ List of ``DeprecationWrapperInfo`` instances whose ``args_mapping_positional_only`` field is
1494
+ non-empty. Returns an empty list when no incompatibilities are found.
1495
+
1496
+ Examples:
1497
+ >>> from deprecate import validate_mapping_compatibility
1498
+ >>> import tests.collection_deprecate as col
1499
+ >>> results = validate_mapping_compatibility(col, recursive=False)
1500
+ >>> len(results) > 0 # DepPositionalOnly remaps to a POSITIONAL_ONLY param
1501
+ True
1502
+ >>> results[0].function
1503
+ 'DepPositionalOnly'
1504
+
1505
+ """
1506
+ return [
1507
+ info for info in find_deprecation_wrappers(module, recursive=recursive) if info.args_mapping_positional_only
1508
+ ]
1509
+
1510
+
1511
+ # ---------------------------------------------------------------------------
1512
+ # Backward-compatibility shims — deprecated since 0.6, removed in 1.0
1513
+ # ---------------------------------------------------------------------------
1514
+
1515
+ # Import delayed to avoid a module-level circular import cycle:
1516
+ # audit.py is imported by __init__.py before deprecation.py is available.
1517
+ from deprecate.deprecation import deprecated # noqa: E402
1518
+
1519
+
1520
+ @deprecated(target=validate_deprecation_wrapper, deprecated_in="0.6", remove_in="1.0")
1521
+ def validate_deprecated_callable(func: Callable) -> DeprecationWrapperInfo:
1522
+ """Use :func:`~deprecate.audit.validate_deprecation_wrapper` instead."""
1523
+ return validate_deprecation_wrapper(func)
1524
+
1525
+
1526
+ @deprecated(target=find_deprecation_wrappers, deprecated_in="0.6", remove_in="1.0")
1527
+ def find_deprecated_callables(
1528
+ module: Union[Any, str], # noqa: ANN401
1529
+ recursive: bool = True,
1530
+ ) -> list[DeprecationWrapperInfo]:
1531
+ """Use :func:`~deprecate.audit.find_deprecation_wrappers` instead."""
1532
+ return find_deprecation_wrappers(module, recursive)
1533
+
1534
+
1535
+ @deprecated_class(target=DeprecationWrapperInfo, deprecated_in="0.6", remove_in="1.0")
1536
+ class DeprecatedCallableInfo:
1537
+ """Deprecated name for :class:`~deprecate.audit.DeprecationWrapperInfo`, use that instead."""
.venv/lib/python3.12/site-packages/deprecate/deprecation.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/deprecate/docstring/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """Docstring utilities for pyDeprecate.
2
+
3
+ Sub-modules:
4
+
5
+ - :mod:`deprecate.docstring.inject` — runtime docstring injection logic.
6
+ - :mod:`deprecate.docstring.griffe_ext` — Griffe extension for mkdocstrings / MkDocs. *(beta)*
7
+ - :mod:`deprecate.docstring.sphinx_ext` — Sphinx autodoc extension. *(beta)*
8
+
9
+ """
.venv/lib/python3.12/site-packages/deprecate/docstring/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (518 Bytes). View file
 
.venv/lib/python3.12/site-packages/deprecate/docstring/__pycache__/griffe_ext.cpython-312.pyc ADDED
Binary file (6.53 kB). View file
 
.venv/lib/python3.12/site-packages/deprecate/docstring/__pycache__/inject.cpython-312.pyc ADDED
Binary file (28.3 kB). View file
 
.venv/lib/python3.12/site-packages/deprecate/docstring/__pycache__/sphinx_ext.cpython-312.pyc ADDED
Binary file (6.41 kB). View file
 
.venv/lib/python3.12/site-packages/deprecate/docstring/griffe_ext.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Griffe extension: expose runtime-modified docstrings to mkdocstrings.
2
+
3
+ .. note::
4
+ **Beta feature** — the public API of this module (class name, hook method
5
+ signatures) may change in a minor release while it stabilises.
6
+
7
+ ``@deprecated(update_docstring=True)`` writes the deprecation notice into
8
+ ``fn.__doc__`` at decoration time. Griffe — the engine used by mkdocstrings —
9
+ reads docstrings from the source AST, so it never sees that runtime change.
10
+
11
+ This extension bridges the gap: after Griffe has visited a module it imports
12
+ the module at runtime and replaces every AST docstring whose callable carries
13
+ a ``__deprecated__`` attribute (set by pyDeprecate) with the live ``__doc__``.
14
+
15
+ Usage in ``mkdocs.yml``::
16
+
17
+ plugins:
18
+ - mkdocstrings:
19
+ handlers:
20
+ python:
21
+ options:
22
+ extensions:
23
+ - deprecate.docstring.griffe_ext:RuntimeDocstrings
24
+
25
+ Requirements:
26
+ ``griffe`` is a dependency of ``mkdocstrings[python]`` and will always be
27
+ present in an MkDocs environment that uses mkdocstrings. Importing this
28
+ module without ``griffe`` installed is safe — ``RuntimeDocstrings`` simply
29
+ will not be defined.
30
+
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import importlib
36
+ import sys
37
+
38
+ try:
39
+ import griffe
40
+ except ImportError:
41
+ pass
42
+ else:
43
+
44
+ class RuntimeDocstrings(griffe.Extension):
45
+ """Update Griffe docstrings to reflect decorator-modified ``__doc__``."""
46
+
47
+ def on_module(self, *, mod: griffe.Module, loader: griffe.GriffeLoader, **kwargs: object) -> None:
48
+ """Run after a module is fully loaded by Griffe.
49
+
50
+ For each function or method in *mod* that carries a ``__deprecated__`` attribute (set by pyDeprecate),
51
+ replace the Griffe docstring with the runtime value so that mkdocstrings renders the injected notice.
52
+
53
+ """
54
+ runtime_mod = self._import_module(mod)
55
+ if runtime_mod is None:
56
+ return
57
+
58
+ for name, obj in mod.members.items():
59
+ if isinstance(obj, griffe.Object):
60
+ self._update_obj(obj, runtime_mod, name)
61
+
62
+ @staticmethod
63
+ def _import_module(mod: griffe.Module) -> object:
64
+ """Import *mod* at runtime, adding its package root to sys.path if needed.
65
+
66
+ griffe loads modules via its own search_paths which are not on sys.path, so a plain
67
+ ``importlib.import_module(mod.name)`` will fail for modules that live outside the installed packages (e.g. a
68
+ local ``demo.py``). We derive the package root from ``mod.filepath`` — walking up one level per dotted name
69
+ component so that both single-file modules (``demo``) and package sub-modules (``pkg.submod``) resolve
70
+ correctly — and temporarily add it to sys.path so the import can succeed.
71
+
72
+ """
73
+ # Fast path: module is already importable (installed package, etc.)
74
+ try:
75
+ return importlib.import_module(mod.name)
76
+ except (ImportError, ModuleNotFoundError):
77
+ pass
78
+
79
+ # Slow path: add the package root derived from mod.filepath.
80
+ filepath = getattr(mod, "filepath", None)
81
+ if filepath is None:
82
+ return None
83
+
84
+ import pathlib
85
+
86
+ # Walk up one level per name component so sys.path contains the
87
+ # *root* of the package tree, not a sub-directory.
88
+ # Examples (depth before __init__ adjustment):
89
+ # "demo" /project/demo.py → depth=0, parents[0]=/project ✓
90
+ # "pkg.sub" /project/pkg/sub.py → depth=1, parents[1]=/project ✓
91
+ # For packages the filepath points to __init__.py, adding one more
92
+ # level:
93
+ # "pkg" /project/pkg/__init__.py → depth=0+1=1, parents[1]=/project ✓
94
+ # "pkg.sub" /project/pkg/sub/__init__.py → depth=1+1=2, parents[2]=/project ✓
95
+ p = pathlib.Path(filepath)
96
+ depth = len(mod.name.split(".")) - 1
97
+ if p.name == "__init__.py":
98
+ depth += 1
99
+ source_dir = str(p.parents[depth])
100
+ added = source_dir not in sys.path
101
+ if added:
102
+ sys.path.insert(0, source_dir)
103
+ try:
104
+ return importlib.import_module(mod.name)
105
+ except (ImportError, ModuleNotFoundError):
106
+ return None
107
+ finally:
108
+ if added:
109
+ sys.path.remove(source_dir)
110
+
111
+ def _update_obj(self, obj: griffe.Object, parent: object, name: str) -> None:
112
+ """Patch obj with runtime deprecation metadata from the live import."""
113
+ runtime_obj = getattr(parent, name, None)
114
+ if runtime_obj is None:
115
+ return
116
+
117
+ if isinstance(obj, griffe.Function):
118
+ self._replace_docstring(obj, runtime_obj)
119
+ elif isinstance(obj, griffe.Class):
120
+ self._replace_docstring(obj, runtime_obj)
121
+ for member_name, member in obj.members.items():
122
+ if isinstance(member, griffe.Object):
123
+ self._update_obj(member, runtime_obj, member_name)
124
+
125
+ @staticmethod
126
+ def _replace_docstring(griffe_obj: griffe.Object, runtime_obj: object) -> None:
127
+ """Overwrite the Griffe docstring when the runtime ``__doc__`` differs."""
128
+ if not getattr(runtime_obj, "__deprecated__", None):
129
+ return
130
+ runtime_doc = getattr(runtime_obj, "__doc__", None)
131
+ if not runtime_doc:
132
+ return
133
+ if griffe_obj.docstring is None:
134
+ return
135
+ griffe_obj.docstring.value = runtime_doc
136
+ # Griffe caches parsed sections in docstring.__dict__["parsed"].
137
+ # If the cache was populated from the static source before this
138
+ # extension ran, it must be cleared so the next access re-parses from the updated value.
139
+ griffe_obj.docstring.__dict__.pop("parsed", None)
.venv/lib/python3.12/site-packages/deprecate/docstring/inject.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers for annotating function docstrings with deprecation information.
2
+
3
+ This module owns all logic that reads or modifies a callable's ``__doc__``
4
+ attribute during deprecation decoration. It supports both Google-style
5
+ (``Args:`` / ``Arguments:``), NumPy-style (``Parameters`` + underline),
6
+ and Sphinx-style (``:param ...:``) docstrings, plus MkDocs/Markdown output.
7
+
8
+ Key Components:
9
+ - String constants (``TEMPLATE_DOC_*``) for reusable message fragments.
10
+ - Style normalizer: :func:`normalize_docstring_style`, :func:`_auto_detect_style`
11
+ - Section-aware insertion helpers: :func:`find_docstring_insertion_index`,
12
+ :func:`is_numpy_underline`
13
+ - Per-argument note builder: :func:`_build_arg_deprecation_note`
14
+ - Google-style section helpers: :func:`_find_google_args_section`,
15
+ :func:`_get_google_arg_indents`, :func:`_find_google_arg_line`
16
+ - Shared continuation-line helper: :func:`_find_entry_end`
17
+ - Annotators: :func:`_annotate_google_style_arg`,
18
+ :func:`_annotate_sphinx_style_arg`
19
+ - Notice builder: :func:`_build_general_notice_lines`
20
+ - Orchestrator: :func:`_update_docstring_with_deprecation`
21
+
22
+ Copyright (C) 2020-2026 Jiri Borovec <6035284+Borda@users.noreply.github.com>
23
+
24
+ """
25
+
26
+ import inspect
27
+ import os
28
+ import re
29
+ import sys
30
+ from typing import Literal, Optional, cast
31
+
32
+ from deprecate._types import (
33
+ DeprecationConfig,
34
+ TargetMode,
35
+ _has_deprecation_meta,
36
+ )
37
+
38
+ #: Default templates for documentation with deprecated callable — RST/Sphinx style
39
+ TEMPLATE_DOC_DEPRECATED_RST = [
40
+ ".. deprecated:: %(deprecated_in)s",
41
+ " %(remove_text)s",
42
+ " %(target_text)s",
43
+ ]
44
+ #: Default templates for documentation with deprecated callable — MkDocs/Markdown style
45
+ TEMPLATE_DOC_DEPRECATED_MKDOCS = [
46
+ '!!! warning "Deprecated in %(deprecated_in)s"',
47
+ " %(remove_text)s",
48
+ " %(target_text)s",
49
+ ]
50
+ #: Inline docstring note for a deprecated argument — with ``deprecated_in`` version
51
+ TEMPLATE_DOC_ARG_DEPRECATED_SINCE = "Deprecated since v%(deprecated_in)s \u2014 %(reason)s."
52
+ #: Inline docstring note for a deprecated argument — without version information
53
+ TEMPLATE_DOC_ARG_DEPRECATED = "Deprecated \u2014 %(reason)s."
54
+ #: Suffix appended to arg deprecation note when ``remove_in`` is provided
55
+ TEMPLATE_DOC_ARG_REMOVE = " Will be removed in v%(remove_in)s."
56
+ #: Reason phrase used when the deprecated argument is simply removed
57
+ TEMPLATE_DOC_ARG_REASON_REMOVED = "no longer used"
58
+ #: Reason phrase used when the deprecated argument is renamed; ``%(new_arg)s`` is substituted
59
+ TEMPLATE_DOC_ARG_REASON_RENAMED = "use `%(new_arg)s` instead"
60
+
61
+ DOCSTRING_STYLE_ALIASES = {"auto": "auto", "rst": "rst", "mkdocs": "mkdocs", "markdown": "mkdocs"}
62
+ SUPPORTED_DOCSTRING_STYLES: frozenset[str] = frozenset(DOCSTRING_STYLE_ALIASES)
63
+ GOOGLE_DOCSTRING_SECTIONS = {
64
+ "args:",
65
+ "arguments:",
66
+ "attributes:",
67
+ "examples:",
68
+ "notes:",
69
+ "parameters:",
70
+ "raises:",
71
+ "returns:",
72
+ "warns:",
73
+ "yields:",
74
+ }
75
+ NUMPY_DOCSTRING_SECTIONS = {
76
+ "attributes",
77
+ "examples",
78
+ "methods",
79
+ "notes",
80
+ "other parameters",
81
+ "parameters",
82
+ "raises",
83
+ "returns",
84
+ "warns",
85
+ "yields",
86
+ }
87
+
88
+
89
+ def is_numpy_underline(line: str) -> bool:
90
+ """Return ``True`` when the line is a NumPy-style section underline."""
91
+ stripped = line.strip()
92
+ return len(stripped) >= 3 and all(char == "-" for char in stripped)
93
+
94
+
95
+ def find_docstring_insertion_index(lines: list[str]) -> int:
96
+ """Find insertion index before first Google/NumPy section header."""
97
+ for idx, line in enumerate(lines):
98
+ if line.strip().lower() in GOOGLE_DOCSTRING_SECTIONS:
99
+ return idx
100
+ if (
101
+ idx + 1 < len(lines)
102
+ and line.strip().lower() in NUMPY_DOCSTRING_SECTIONS
103
+ and is_numpy_underline(lines[idx + 1])
104
+ ):
105
+ return idx
106
+ return len(lines)
107
+
108
+
109
+ def _auto_detect_style() -> Literal["rst", "mkdocs"]:
110
+ """Detect documentation engine from environment or process name.
111
+
112
+ Resolution order:
113
+
114
+ 1. ``DEPRECATE_DOCSTRING_STYLE`` env var — explicit override, takes highest priority.
115
+ 2. ``sys.modules`` — ``mkdocs`` imported → MkDocs build in progress.
116
+ 3. ``sys.argv[0]`` full path — ``mkdocs`` anywhere in the path string.
117
+ 4. Default → ``"rst"``.
118
+
119
+ """
120
+ env_style = os.environ.get("DEPRECATE_DOCSTRING_STYLE", "").lower()
121
+ if env_style in ("mkdocs", "markdown"):
122
+ return "mkdocs"
123
+ if env_style == "rst":
124
+ return "rst"
125
+ # sys.modules check catches `python -m mkdocs` where argv[0] is __main__.py
126
+ if "mkdocs" in sys.modules:
127
+ return "mkdocs"
128
+ if sys.argv and "mkdocs" in sys.argv[0].lower():
129
+ return "mkdocs"
130
+ return "rst"
131
+
132
+
133
+ def normalize_docstring_style(docstring_style: str) -> Literal["rst", "mkdocs"]:
134
+ """Validate and normalize docstring style aliases."""
135
+ if not isinstance(docstring_style, str):
136
+ raise ValueError(
137
+ "Invalid `docstring_style` value "
138
+ f"{docstring_style!r}. Supported styles are: {sorted(SUPPORTED_DOCSTRING_STYLES)!r}."
139
+ )
140
+ normalized_style = DOCSTRING_STYLE_ALIASES.get(docstring_style.lower())
141
+ if normalized_style is None:
142
+ raise ValueError(
143
+ "Invalid `docstring_style` value "
144
+ f"{docstring_style!r}. Supported styles are: {sorted(SUPPORTED_DOCSTRING_STYLES)!r}."
145
+ )
146
+ if normalized_style == "auto":
147
+ return _auto_detect_style()
148
+ return cast(Literal["rst", "mkdocs"], normalized_style)
149
+
150
+
151
+ def _build_arg_deprecation_note(new_arg: Optional[str], deprecated_in: str, remove_in: str) -> str:
152
+ """Build an inline deprecation note string for a single deprecated argument.
153
+
154
+ Args:
155
+ new_arg: Replacement argument name, or ``None`` when the argument is simply removed.
156
+ deprecated_in: Version string when the argument was deprecated (e.g. ``"1.8"``).
157
+ remove_in: Version string when the argument will be removed (e.g. ``"1.9"``).
158
+
159
+ Returns:
160
+ A one-line deprecation note suitable for embedding in a docstring.
161
+
162
+ Example:
163
+ >>> _build_arg_deprecation_note(None, "1.8", "1.9")
164
+ 'Deprecated since v1.8 — no longer used. Will be removed in v1.9.'
165
+ >>> _build_arg_deprecation_note("new_arg", "1.8", "1.9")
166
+ 'Deprecated since v1.8 — use `new_arg` instead. Will be removed in v1.9.'
167
+
168
+ """
169
+ reason = TEMPLATE_DOC_ARG_REASON_RENAMED % {"new_arg": new_arg} if new_arg else TEMPLATE_DOC_ARG_REASON_REMOVED
170
+ template = TEMPLATE_DOC_ARG_DEPRECATED_SINCE if deprecated_in else TEMPLATE_DOC_ARG_DEPRECATED
171
+ note = template % {"deprecated_in": deprecated_in, "reason": reason}
172
+ if remove_in:
173
+ note += TEMPLATE_DOC_ARG_REMOVE % {"remove_in": remove_in}
174
+ return note
175
+
176
+
177
+ def _find_google_args_section(lines: list[str]) -> tuple[int, int]:
178
+ """Return ``(section_start, section_indent)`` for a Google-style ``Args:`` header.
179
+
180
+ Scans *lines* for an ``Args:`` or ``Arguments:`` header and returns its line
181
+ index and leading indentation. Returns ``(-1, 0)`` when not found.
182
+
183
+ The match is intentionally strict: a line qualifies only when it consists
184
+ of optional leading spaces followed by exactly ``Args:`` or ``Arguments:``
185
+ with nothing else on the line (no trailing text). This avoids accidental
186
+ matches inside prose paragraphs.
187
+
188
+ See `Google Python Style Guide — Functions and Methods
189
+ <https://google.github.io/styleguide/pyguide.html#383-functions-and-methods>`_
190
+ for the ``Args:`` section specification.
191
+
192
+ Args:
193
+ lines: Docstring already split into individual lines.
194
+
195
+ Returns:
196
+ A 2-tuple ``(section_start, section_indent)``.
197
+
198
+ """
199
+ _section_re = re.compile(r"^\s*(Args|Arguments):\s*$")
200
+ for i, line in enumerate(lines):
201
+ if _section_re.match(line):
202
+ return i, len(line) - len(line.lstrip())
203
+ return -1, 0
204
+
205
+
206
+ def _get_google_arg_indents(lines: list[str], section_start: int, section_indent: int) -> tuple[int, int]:
207
+ """Return ``(arg_indent, continuation_indent)`` for a Google-style Args section.
208
+
209
+ *arg_indent* is the column at which individual argument entries begin.
210
+ *continuation_indent* is the column used for continuation lines within an
211
+ argument entry (defaults to ``arg_indent + 4`` when not detectable).
212
+ Returns ``(-1, -1)`` when the section has no non-empty child lines.
213
+
214
+ Args:
215
+ lines: Docstring already split into individual lines.
216
+ section_start: Line index of the ``Args:`` / ``Arguments:`` header.
217
+ section_indent: Leading indentation of that header line.
218
+
219
+ Returns:
220
+ A 2-tuple ``(arg_indent, continuation_indent)``.
221
+
222
+ """
223
+ arg_indent = -1
224
+ for i in range(section_start + 1, len(lines)):
225
+ if lines[i].strip():
226
+ current_indent = len(lines[i]) - len(lines[i].lstrip())
227
+ if current_indent > section_indent:
228
+ arg_indent = current_indent
229
+ break
230
+
231
+ if arg_indent == -1:
232
+ return -1, -1
233
+
234
+ continuation_indent = arg_indent + 4
235
+ for i in range(section_start + 1, len(lines)):
236
+ line = lines[i]
237
+ if not line.strip():
238
+ continue
239
+ current_indent = len(line) - len(line.lstrip())
240
+ if current_indent <= section_indent:
241
+ break
242
+ if current_indent > arg_indent:
243
+ continuation_indent = current_indent
244
+ break
245
+
246
+ return arg_indent, continuation_indent
247
+
248
+
249
+ def _find_google_arg_line(
250
+ lines: list[str], section_start: int, section_indent: int, arg_indent: int, arg_name: str
251
+ ) -> int:
252
+ """Return the line index of *arg_name* inside a Google-style Args section.
253
+
254
+ Returns ``-1`` when *arg_name* is not found within the section.
255
+
256
+ Args:
257
+ lines: Docstring already split into individual lines.
258
+ section_start: Line index of the ``Args:`` / ``Arguments:`` header.
259
+ section_indent: Leading indentation of that header line.
260
+ arg_indent: Leading indentation of argument entry lines.
261
+ arg_name: Name of the argument to locate.
262
+
263
+ Returns:
264
+ Line index of the matching argument entry, or ``-1``.
265
+
266
+ """
267
+ for i in range(section_start + 1, len(lines)):
268
+ line = lines[i]
269
+ if not line.strip():
270
+ continue
271
+ current_indent = len(line) - len(line.lstrip())
272
+ if current_indent <= section_indent:
273
+ break
274
+ if current_indent == arg_indent:
275
+ rest = line[arg_indent:]
276
+ has_arg_boundary = len(rest) > len(arg_name) and rest[len(arg_name)] in " :(,"
277
+ if rest == arg_name or (rest.startswith(arg_name) and has_arg_boundary):
278
+ return i
279
+ return -1
280
+
281
+
282
+ def _find_entry_end(lines: list[str], entry_idx: int, entry_indent: int) -> int:
283
+ """Return the index of the last continuation line for a docstring entry.
284
+
285
+ Scans forward from *entry_idx + 1* and stops at the first blank line or
286
+ the first line whose indentation is ``<= entry_indent``.
287
+
288
+ Note:
289
+ A blank line within a multi-paragraph argument description is treated
290
+ as the entry boundary. Only the content up to that blank line receives
291
+ the deprecation note; subsequent paragraphs are considered outside the
292
+ entry.
293
+
294
+ Args:
295
+ lines: Docstring already split into individual lines.
296
+ entry_idx: Line index of the entry's opening line.
297
+ entry_indent: Leading indentation of that opening line.
298
+
299
+ Returns:
300
+ Index of the last line belonging to the entry (>= *entry_idx*).
301
+
302
+ """
303
+ end_idx = entry_idx
304
+ for i in range(entry_idx + 1, len(lines)):
305
+ line = lines[i]
306
+ if not line.strip():
307
+ break
308
+ if len(line) - len(line.lstrip()) <= entry_indent:
309
+ break
310
+ end_idx = i
311
+ return end_idx
312
+
313
+
314
+ def _annotate_google_style_arg(lines: list[str], arg_name: str, note: str) -> tuple[list[str], bool]:
315
+ """Find *arg_name* in a Google-style ``Args:`` section and insert *note* below it.
316
+
317
+ Supports both ``Args:`` and ``Arguments:`` section headers. Returns the
318
+ original list unchanged when no matching section or argument entry is found.
319
+
320
+ Args:
321
+ lines: Docstring already split into individual lines.
322
+ arg_name: Name of the deprecated argument to locate.
323
+ note: Text to insert as a continuation line under the matched entry.
324
+
325
+ Returns:
326
+ A 2-tuple ``(new_lines, found)`` where *found* is ``True`` when the
327
+ argument was located and the note was successfully inserted.
328
+
329
+ The note is inserted as a continuation line directly after the matched entry:
330
+
331
+ .. code-block:: text
332
+
333
+ Args:
334
+ lr (float): Learning rate.
335
+ old_cfg (object): Old config.
336
+ Deprecated — use cfg instead. # <-- inserted here
337
+
338
+ """
339
+ section_start, section_indent = _find_google_args_section(lines)
340
+ if section_start == -1:
341
+ return lines, False
342
+
343
+ arg_indent, continuation_indent = _get_google_arg_indents(lines, section_start, section_indent)
344
+ if arg_indent == -1:
345
+ return lines, False
346
+
347
+ arg_line_idx = _find_google_arg_line(lines, section_start, section_indent, arg_indent, arg_name)
348
+ if arg_line_idx == -1:
349
+ return lines, False
350
+
351
+ end_idx = _find_entry_end(lines, arg_line_idx, arg_indent)
352
+ # Idempotency guard: skip insertion when the note is already present under this arg entry.
353
+ if any(note in ln for ln in lines[arg_line_idx : end_idx + 1]):
354
+ return lines, True
355
+ note_line = " " * continuation_indent + note
356
+ new_lines = lines[: end_idx + 1] + [note_line] + lines[end_idx + 1 :]
357
+ return new_lines, True
358
+
359
+
360
+ def _annotate_sphinx_style_arg(lines: list[str], arg_name: str, note: str) -> tuple[list[str], bool]:
361
+ """Find ``:param arg_name:`` in a Sphinx-style docstring and insert *note* below it.
362
+
363
+ Supports both ``:param arg_name:`` and ``:param SomeType arg_name:`` forms.
364
+ Returns the original list unchanged when no matching ``:param`` field is found.
365
+
366
+ Args:
367
+ lines: Docstring already split into individual lines.
368
+ arg_name: Name of the deprecated argument to locate.
369
+ note: Text to insert as a continuation line under the matched field.
370
+
371
+ Returns:
372
+ A 2-tuple ``(new_lines, found)`` where *found* is ``True`` when the
373
+ parameter was located and the note was successfully inserted.
374
+
375
+ The note is inserted as a continuation line directly after the matched field::
376
+
377
+ :param lr: Learning rate.
378
+ :param old_cfg: Old config.
379
+ Deprecated — use cfg instead. # <-- inserted here
380
+ :returns: Result.
381
+
382
+ """
383
+ pattern = re.compile(r"^(\s*):param\s+(?:\S+\s+)?" + re.escape(arg_name) + r"\s*:")
384
+
385
+ param_line_idx = -1
386
+ param_indent = 0
387
+ for i, line in enumerate(lines):
388
+ m = pattern.match(line)
389
+ if m:
390
+ param_line_idx = i
391
+ param_indent = len(m.group(1))
392
+ break
393
+
394
+ if param_line_idx == -1:
395
+ return lines, False
396
+
397
+ end_idx = _find_entry_end(lines, param_line_idx, param_indent)
398
+ # Idempotency guard: skip insertion when the note is already present under this param entry.
399
+ if any(note in ln for ln in lines[param_line_idx : end_idx + 1]):
400
+ return lines, True
401
+ note_line = " " * (param_indent + 4) + note
402
+ new_lines = lines[: end_idx + 1] + [note_line] + lines[end_idx + 1 :]
403
+ return new_lines, True
404
+
405
+
406
+ def _build_general_notice_lines(dep_info: DeprecationConfig) -> list[str]:
407
+ """Render the general deprecation notice lines for the given style.
408
+
409
+ Selects the RST (``.. deprecated::``) or MkDocs (``!!! warning``) template
410
+ based on ``dep_info.docstring_style``, substitutes ``deprecated_in``,
411
+ ``remove_in``, and the target reference, and omits template lines whose
412
+ placeholder resolves to an empty string.
413
+
414
+ Args:
415
+ dep_info: Frozen deprecation metadata attached to the decorated callable.
416
+
417
+ Returns:
418
+ A list of rendered notice lines (without leading body indentation).
419
+
420
+ """
421
+ remove_text = f"Will be removed in {dep_info.remove_in}." if dep_info.remove_in else ""
422
+ target_text_rst = ""
423
+ target_text_mkdocs = ""
424
+ if callable(dep_info.target):
425
+ full_target_name = f"{dep_info.target.__module__}.{dep_info.target.__name__}"
426
+ ref_type = "class" if inspect.isclass(dep_info.target) else "func"
427
+ target_text_rst = f"Use :{ref_type}:`{full_target_name}` instead."
428
+ target_text_mkdocs = f"Use `{full_target_name}` instead."
429
+
430
+ docstring_style = normalize_docstring_style(dep_info.docstring_style)
431
+ if docstring_style == "mkdocs":
432
+ template = TEMPLATE_DOC_DEPRECATED_MKDOCS
433
+ target_text = target_text_mkdocs
434
+ else:
435
+ template = TEMPLATE_DOC_DEPRECATED_RST
436
+ target_text = target_text_rst
437
+
438
+ result = []
439
+ for line in template:
440
+ if line.strip().endswith("%(remove_text)s") and not remove_text:
441
+ continue
442
+ if line.strip().endswith("%(target_text)s") and not target_text:
443
+ continue
444
+ result.append(
445
+ line % {"deprecated_in": dep_info.deprecated_in, "remove_text": remove_text, "target_text": target_text}
446
+ )
447
+ return result
448
+
449
+
450
+ def _has_deprecation_block(doc_lines: list[str], block_lines: list[str]) -> bool:
451
+ """Return True if ``block_lines`` appears as a contiguous block in ``doc_lines``.
452
+
453
+ Lines are compared using ``.strip()`` to ignore leading/trailing whitespace.
454
+
455
+ """
456
+ if not block_lines:
457
+ return False
458
+ max_start = len(doc_lines) - len(block_lines)
459
+ if max_start < 0:
460
+ return False
461
+ first = block_lines[0].strip()
462
+ for start in range(max_start + 1):
463
+ if doc_lines[start].strip() != first:
464
+ continue
465
+ if all(doc_lines[start + offset].strip() == block_lines[offset].strip() for offset in range(len(block_lines))):
466
+ return True
467
+ return False
468
+
469
+
470
+ def _inject_args_mapping_section(lines: list[str], dep_info: DeprecationConfig) -> tuple[list[str], bool]:
471
+ """Apply per-argument inline deprecation notes to docstring lines.
472
+
473
+ Returns ``(updated_lines, all_args_found)`` where ``all_args_found`` is ``True`` when every key in
474
+ ``dep_info.args_mapping`` was located in the docstring.
475
+
476
+ """
477
+ all_args_found = True
478
+ for arg_name, new_arg in (dep_info.args_mapping or {}).items():
479
+ note = _build_arg_deprecation_note(new_arg, dep_info.deprecated_in, dep_info.remove_in)
480
+ lines, found = _annotate_google_style_arg(lines, arg_name, note)
481
+ if not found:
482
+ lines, found = _annotate_sphinx_style_arg(lines, arg_name, note)
483
+ if not found:
484
+ all_args_found = False
485
+ return lines, all_args_found
486
+
487
+
488
+ def _append_notice_after_inline_args(lines: list[str], body_indent: str, deprecation_lines: list[str]) -> list[str]:
489
+ """Append general deprecation notice after inline per-arg annotations."""
490
+ while lines and not lines[-1].strip():
491
+ lines.pop()
492
+ lines.append("")
493
+ lines.extend(body_indent + ln for ln in deprecation_lines)
494
+ return lines
495
+
496
+
497
+ def _insert_notice_before_section(lines: list[str], body_indent: str, deprecation_lines: list[str]) -> str:
498
+ """Insert general deprecation notice before the first Google/NumPy section header."""
499
+ indented = [body_indent + ln for ln in deprecation_lines]
500
+ insert_idx = find_docstring_insertion_index(lines)
501
+ prefix = lines[:insert_idx]
502
+ suffix = lines[insert_idx:]
503
+ if prefix and prefix[-1].strip():
504
+ prefix.append("")
505
+ prefix.extend(indented)
506
+ if suffix:
507
+ while suffix and not suffix[-1].strip(): # Python 3.13 may leave trailing blanks
508
+ suffix.pop()
509
+ if suffix and suffix[0].strip():
510
+ prefix.append("")
511
+ prefix.extend(suffix)
512
+ return "\n".join(prefix)
513
+
514
+
515
+ def _update_docstring_with_deprecation(wrapped_fn: object) -> None:
516
+ """Annotate a function's docstring with deprecation information.
517
+
518
+ Two paths are taken depending on whether ``args_mapping`` is set:
519
+
520
+ - **Inline arg path** (``args_mapping`` present): each deprecated argument is
521
+ located in the ``Args:`` / ``Arguments:`` (Google style) or ``:param``
522
+ (Sphinx style) section and a one-line deprecation note is inserted directly
523
+ beneath it. When ``target`` is ``True`` (self-deprecation) and all deprecated
524
+ args are found, the function returns early and no general notice block is
525
+ added. When ``target`` is a callable or ``None``, the general block is
526
+ always added after the inline annotations because the function itself is
527
+ deprecated.
528
+ - **General notice path** (no ``args_mapping``, or at least one arg was not
529
+ found in the docstring): a deprecation notice is inserted before the first
530
+ Google/NumPy section header (e.g. ``Args:``, ``Parameters``) when detected,
531
+ otherwise appended at the end of the docstring. The notice format depends
532
+ on ``docstring_style``: Sphinx ``.. deprecated::`` directive (default
533
+ ``"rst"``) or MkDocs/Markdown admonition (``"mkdocs"``/``"markdown"``).
534
+
535
+ Args:
536
+ wrapped_fn: Function whose docstring should be updated. Must have
537
+ ``__deprecated__`` attribute set with deprecation metadata.
538
+
539
+ Returns:
540
+ None. Modifies the function's ``__doc__`` attribute in-place.
541
+
542
+ Metadata Used:
543
+ The function's ``__deprecated__`` attribute should be a
544
+ :class:`~deprecate._types.DeprecationConfig` instance with:
545
+ - deprecated_in: Version when deprecated
546
+ - remove_in: Version when will be removed
547
+ - target: Replacement callable (optional)
548
+ - args_mapping: Mapping of old → new argument names (optional)
549
+
550
+ Example:
551
+ General notice path — no ``args_mapping``:
552
+
553
+ >>> def new_func(): pass
554
+ >>> def old_func():
555
+ ... '''Original docstring.'''
556
+ ... pass
557
+ >>> old_func.__deprecated__ = DeprecationConfig(
558
+ ... deprecated_in='1.0',
559
+ ... remove_in='2.0',
560
+ ... target=new_func,
561
+ ... )
562
+ >>> _update_docstring_with_deprecation(old_func)
563
+ >>> print(old_func.__doc__) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
564
+ Original docstring.
565
+ <BLANKLINE>
566
+ .. deprecated:: 1.0
567
+ Will be removed in 2.0.
568
+ Use :func:`...new_func` instead.
569
+
570
+ Inline arg path — self-deprecation (``target=True``) with all args found:
571
+
572
+ >>> def fn_with_args(x: int, old_arg: str = "") -> str:
573
+ ... '''Do something.
574
+ ...
575
+ ... Args:
576
+ ... x: The main input.
577
+ ... old_arg: The old argument.
578
+ ... '''
579
+ ... return str(x)
580
+ >>> fn_with_args.__deprecated__ = DeprecationConfig(
581
+ ... deprecated_in='1.0',
582
+ ... remove_in='2.0',
583
+ ... target=TargetMode.ARGS_REMAP,
584
+ ... args_mapping={'old_arg': None},
585
+ ... )
586
+ >>> _update_docstring_with_deprecation(fn_with_args)
587
+ >>> 'Deprecated since v1.0' in fn_with_args.__doc__
588
+ True
589
+ >>> '.. deprecated::' in fn_with_args.__doc__
590
+ False
591
+
592
+ Note:
593
+ Does nothing if the function has no docstring or no ``__deprecated__`` attribute.
594
+ To preserve Google/NumPy parsing, the general notice is inserted before the
595
+ first section header (e.g. ``Args:`` or ``Parameters``) when detected.
596
+
597
+ """
598
+ if not hasattr(wrapped_fn, "__doc__") or not wrapped_fn.__doc__:
599
+ return
600
+ if not _has_deprecation_meta(wrapped_fn):
601
+ return
602
+ lines = wrapped_fn.__doc__.splitlines()
603
+ dep_info = wrapped_fn.__deprecated__
604
+
605
+ if dep_info.args_mapping:
606
+ lines, all_args_found = _inject_args_mapping_section(lines, dep_info)
607
+ # ARGS_REMAP (or legacy target=True) means only individual args are deprecated,
608
+ # not the function itself.
609
+ if all_args_found and dep_info.target is TargetMode.ARGS_REMAP:
610
+ wrapped_fn.__doc__ = inspect.cleandoc("\n".join(lines))
611
+ return
612
+
613
+ deprecation_lines = _build_general_notice_lines(dep_info)
614
+
615
+ # Guard idempotency by checking for the full deprecation block, not just the marker line.
616
+ if _has_deprecation_block(lines, deprecation_lines):
617
+ return
618
+ body_indent = next(
619
+ (line[: len(line) - len(line.lstrip())] for line in lines[1:] if line.strip()),
620
+ "",
621
+ )
622
+ if dep_info.args_mapping:
623
+ lines = _append_notice_after_inline_args(lines, body_indent, deprecation_lines)
624
+ wrapped_fn.__doc__ = inspect.cleandoc("\n".join(lines))
625
+ else:
626
+ wrapped_fn.__doc__ = inspect.cleandoc(_insert_notice_before_section(lines, body_indent, deprecation_lines))
.venv/lib/python3.12/site-packages/deprecate/docstring/sphinx_ext.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sphinx autodoc extension: expose runtime-modified docstrings for _DeprecatedProxy.
2
+
3
+ .. note::
4
+ **Beta feature** — the public API of this module (documenter class, priority
5
+ value) may change in a minor release while it stabilises.
6
+
7
+ ``@deprecated_class(update_docstring=True)`` writes the deprecation notice into
8
+ the proxy's ``__doc__`` at decoration time. Sphinx's autodoc sees the proxy as
9
+ a non-class instance and renders it as ``"alias of <target>"`` without showing
10
+ the docstring.
11
+
12
+ This extension bridges the gap by registering a custom :class:`ClassDocumenter`
13
+ that:
14
+
15
+ 1. Recognises :class:`~deprecate.proxy._DeprecatedProxy` objects via
16
+ :meth:`can_document_member`.
17
+ 2. Swaps the proxy for the underlying (wrapped) class so that Sphinx can
18
+ introspect members and build the correct signature.
19
+ 3. Returns the proxy's ``__doc__`` (which already contains the injected
20
+ ``.. deprecated::`` block) from :meth:`get_doc`, so the notice appears in
21
+ the rendered output.
22
+
23
+ Usage in ``conf.py``::
24
+
25
+ extensions = [
26
+ 'sphinx.ext.autodoc',
27
+ ...
28
+ 'deprecate.docstring.sphinx_ext',
29
+ ]
30
+
31
+ Requirements:
32
+ ``sphinx`` with ``sphinx.ext.autodoc`` is required. Importing this module
33
+ without Sphinx installed is safe — the custom documenter is simply not
34
+ registered.
35
+
36
+
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import logging
42
+ from typing import Any
43
+
44
+ _logger = logging.getLogger(__name__)
45
+
46
+ _PROXY_AVAILABLE: bool = False
47
+
48
+ try:
49
+ from sphinx.ext.autodoc import ClassDocumenter
50
+ from sphinx.util.docstrings import prepare_docstring
51
+
52
+ _SPHINX_AVAILABLE = True
53
+ except ImportError: # pragma: no cover
54
+ _SPHINX_AVAILABLE = False
55
+
56
+
57
+ if _SPHINX_AVAILABLE:
58
+ try:
59
+ from deprecate.proxy import _DeprecatedProxy
60
+
61
+ _PROXY_AVAILABLE = True
62
+ except ImportError: # pragma: no cover
63
+ _PROXY_AVAILABLE = False
64
+
65
+ if _PROXY_AVAILABLE:
66
+
67
+ class _DeprecatedProxyClassDocumenter(ClassDocumenter):
68
+ """ClassDocumenter subclass that handles pyDeprecate ``_DeprecatedProxy`` objects.
69
+
70
+ Registered with a priority one step above the standard
71
+ :class:`~sphinx.ext.autodoc.ClassDocumenter` so that it is selected
72
+ whenever ``autoclass::`` is used on a :class:`~deprecate.proxy._DeprecatedProxy`
73
+ instance, while all ordinary classes continue to be handled by the
74
+ built-in documenter.
75
+
76
+ """
77
+
78
+ objtype = "class"
79
+ priority = ClassDocumenter.priority + 5
80
+
81
+ @classmethod
82
+ def can_document_member(
83
+ cls,
84
+ member: Any, # noqa: ANN401
85
+ membername: str,
86
+ isattr: bool,
87
+ parent: Any, # noqa: ANN401
88
+ ) -> bool:
89
+ """Return ``True`` for proxies and for all types the base class accepts."""
90
+ return isinstance(member, _DeprecatedProxy) or super().can_document_member(
91
+ member, membername, isattr, parent
92
+ )
93
+
94
+ def import_object(self, raiseerror: bool = False) -> bool:
95
+ """Import the object and, when it is a proxy, swap it for the wrapped class.
96
+
97
+ The proxy's ``__doc__`` (which contains the injected deprecation notice) is saved in ``self._proxy_doc``
98
+ before the swap so that :meth:`get_doc` can return it verbatim.
99
+
100
+ ``doc_as_attr`` is reset to ``False`` after the swap because the base
101
+ :class:`~sphinx.ext.autodoc.ClassDocumenter` computes it using ``self.object.__name__``. On a
102
+ :class:`~deprecate.proxy._DeprecatedProxy` that attribute is forwarded to the *target* class (via
103
+ ``__getattr__``), which makes Sphinx believe the object is an alias for that target and adds an ``alias
104
+ of …`` paragraph. After the swap ``self.object`` is the real class whose ``__name__`` matches the
105
+ documented path, so ``doc_as_attr`` should be ``False``.
106
+
107
+ """
108
+ result = super().import_object(raiseerror=raiseerror)
109
+ # Use getattr/setattr to avoid mypy confusing the Sphinx-defined
110
+ # `object` attribute with the Python builtin `object` ([has-type]).
111
+ obj: Any = getattr(self, "object", None)
112
+ if result and isinstance(obj, _DeprecatedProxy):
113
+ # Capture the proxy docstring (contains the .. deprecated:: block).
114
+ self._proxy_doc: str = getattr(obj, "__doc__", "") or ""
115
+ # Swap the proxy for the original wrapped class so that
116
+ # ClassDocumenter can introspect members, __init__ signature, etc.
117
+ if hasattr(obj, "_cfg"):
118
+ self.object = obj._cfg.obj
119
+ # Reset doc_as_attr: the base class set it to True because
120
+ # proxy.__name__ (forwarded to the target) differed from the
121
+ # documented name. Now that we have swapped to the real class
122
+ # the name matches and this is not an alias.
123
+ self.doc_as_attr = False
124
+ return result
125
+
126
+ def get_doc(self) -> list[list[str]] | None:
127
+ """Return the proxy docstring so the deprecated block is rendered."""
128
+ proxy_doc: str = getattr(self, "_proxy_doc", "")
129
+ if proxy_doc:
130
+ return [prepare_docstring(proxy_doc)]
131
+ return super().get_doc()
132
+
133
+
134
+ def setup(app: Any) -> dict[str, Any]: # noqa: ANN401
135
+ """Register the ``_DeprecatedProxy`` documenter with Sphinx.
136
+
137
+ Args:
138
+ app: The Sphinx application instance.
139
+
140
+ Returns:
141
+ Extension metadata dict consumed by Sphinx.
142
+
143
+ """
144
+ if _SPHINX_AVAILABLE and _PROXY_AVAILABLE:
145
+ app.setup_extension("sphinx.ext.autodoc")
146
+ # override=True is required because sphinx.ext.autodoc already registers
147
+ # ClassDocumenter for objtype="class" and the autoclass directive.
148
+ app.add_autodocumenter(_DeprecatedProxyClassDocumenter, override=True)
149
+ elif _SPHINX_AVAILABLE:
150
+ _logger.warning(
151
+ "deprecate.docstring.sphinx_ext: _DeprecatedProxy unavailable — "
152
+ "extension loaded but _DeprecatedProxyClassDocumenter not registered."
153
+ )
154
+ return {"version": "0.1", "parallel_read_safe": True}
.venv/lib/python3.12/site-packages/deprecate/proxy.py ADDED
@@ -0,0 +1,1765 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Proxy utilities for deprecating Python object instances and classes.
2
+
3
+ Provides :func:`~deprecate.proxy.deprecated_instance` for wrapping any Python object with
4
+ transparent deprecation warnings and optional read-only enforcement, and
5
+ :func:`~deprecate.proxy.deprecated_class` as a class-level decorator with optional target
6
+ redirection.
7
+
8
+ Typical use cases:
9
+
10
+ - Deprecating module-level config dicts, constants, or legacy singletons
11
+ while still allowing reads during a migration window.
12
+ - Deprecating an Enum or dataclass in favor of a replacement type, with
13
+ automatic forwarding of all attribute, item, and call access.
14
+
15
+ Example:
16
+ >>> import warnings
17
+ >>> cfg = {"threshold": 0.5}
18
+ >>> proxy = deprecated_instance(cfg, deprecated_in="1.0", remove_in="2.0", stream=None)
19
+ >>> proxy["threshold"]
20
+ 0.5
21
+
22
+ >>> proxy.get("threshold")
23
+ 0.5
24
+
25
+ """
26
+
27
+ import copy
28
+ import inspect
29
+ import math
30
+ import operator
31
+ import os
32
+ import threading
33
+ import types
34
+ import warnings
35
+ from collections.abc import Iterator
36
+ from dataclasses import replace
37
+ from typing import Any, Callable, Literal, Optional, SupportsIndex, Union, cast
38
+
39
+ from deprecate._types import (
40
+ DeprecationConfig,
41
+ TargetMode,
42
+ _ProxyConfig,
43
+ )
44
+ from deprecate.deprecation import (
45
+ TEMPLATE_ARGUMENT_MAPPING,
46
+ TEMPLATE_WARNING_ARGUMENTS,
47
+ TEMPLATE_WARNING_CALLABLE,
48
+ TEMPLATE_WARNING_NO_TARGET,
49
+ _split_positional_only_kwargs,
50
+ _validate_template_mgs,
51
+ deprecation_warning,
52
+ )
53
+ from deprecate.docstring.inject import _update_docstring_with_deprecation, normalize_docstring_style
54
+ from deprecate.utils import _apply_args_mapping_collisions, _get_args_mapping_positional_only_keys, _is_dataclass_target
55
+
56
+ #: Stacklevel from inside ``_warn`` to the caller's frame.
57
+ #: Chain: ``caller → __getattr__/__getitem__/__iter__/__call__ → _warn → stream → warnings.warn``.
58
+ #: From ``warnings.warn`` upwards: ``1=_warn``, ``2=accessor``, ``3=caller``.
59
+ #: Helpers one level deeper (e.g. ``_proxy_call_args_remap``) pass ``_extra_frames=1``.
60
+ _DEFAULT_STACKLEVEL_TO_CALLER: int = 3
61
+
62
+
63
+ def _is_dunder(name: str) -> bool:
64
+ """Return whether *name* is a dunder attribute name (``__x__``) — introspection machinery, not user API."""
65
+ return name.startswith("__") and name.endswith("__")
66
+
67
+
68
+ class _DeprecatedProxy:
69
+ """Transparent proxy that emits deprecation warnings on attribute and item access.
70
+
71
+ Wraps any Python object and forwards all read operations (attribute lookup, subscript, iteration, calls) to the
72
+ underlying object — or to an optional *target* replacement — while emitting a configurable :class:`FutureWarning`.
73
+
74
+ In *read-only* mode any attempt to mutate the proxied object via ``__setitem__``, ``__delitem__``, or
75
+ ``__setattr__`` raises :class:`AttributeError`.
76
+
77
+ Use :func:`~deprecate.proxy.deprecated_instance` or :func:`~deprecate.proxy.deprecated_class` to create
78
+ instances rather than instantiating this class directly.
79
+
80
+ Args:
81
+ obj: The deprecated object to wrap (the *source*).
82
+ name: Display name used in the warning message.
83
+ deprecated_in: Version string when the object was deprecated.
84
+ remove_in: Version string when the object will be removed.
85
+ num_warns: Maximum number of warnings to emit. ``1`` (default) warns once; ``-1`` warns on every access.
86
+ stream: Callable used to emit warnings. Defaults to :data:`~deprecate.deprecation.deprecation_warning`
87
+ (:class:`FutureWarning`). Pass ``None`` to suppress warnings. **Note:** the built-in
88
+ stacklevel budget assumes *stream* is :func:`warnings.warn` itself or a C-level
89
+ :func:`functools.partial` of it; a Python-defined wrapper interposes an extra frame and
90
+ the warning will appear to originate inside :mod:`deprecate.proxy` rather than the caller.
91
+ template_mgs: Optional custom warning message template that overrides the built-in templates. When ``None``
92
+ (default), the built-in template for the active scenario is used (callable-target, no-target, or
93
+ per-argument). See :func:`~deprecate.proxy.deprecated_class` for the available ``%``-style placeholders.
94
+ read_only: If ``True``, raise :class:`AttributeError` on any write attempt through the proxy.
95
+ Only the following standard collection mutator names are intercepted: ``append``, ``clear``,
96
+ ``discard``, ``extend``, ``insert``, ``pop``, ``remove``, ``setdefault``, ``update``, ``add``.
97
+ Custom method names (e.g. ``register()``, ``reload()``, ``set_value()``) are not blocked.
98
+ target: Optional replacement object. When set, all attribute, item, and call access is forwarded to *target*
99
+ instead of *obj*.
100
+ args_mapping: Optional dict remapping keyword argument names when the proxy is called. Keys are old argument
101
+ names; values are new names, or ``None`` to drop the argument entirely.
102
+
103
+ Protocol forwarding:
104
+ Operator, conversion, context-manager, iteration, and subclassing protocols are forwarded to the active object
105
+ so the proxy stays transparent (arithmetic ``+ - * / // % ** @`` and their reflected/in-place forms, ordering
106
+ ``< <= > >=``, ``int()``/``float()``/``complex()``/``index()``, ``abs()``/``-``/``+``/``~``,
107
+ ``round()``/``math.trunc``/``floor``/``ceil``, ``reversed()``, ``os.fspath()``, ``format()``,
108
+ ``with``/``async with``, ``next()``/``async for``, ``await``, and ``class Child(DeprecatedAlias)`` via PEP 560
109
+ ``__mro_entries__``). Because implicit special-method lookup bypasses ``__getattr__``, any dunder *not* listed
110
+ here is not forwarded; a protocol the wrapped object does not implement raises the normal :class:`TypeError`
111
+ (binary operators return :data:`NotImplemented` so reflected operands and Python's error path are preserved).
112
+
113
+ **Warn policy** (consistent with ``__getitem__`` vs ``__len__``): operations that use or produce the wrapped
114
+ data warn once against the shared budget — arithmetic and its reflected/in-place forms, numeric/path
115
+ conversions, ``round``/``trunc``/``floor``/``ceil``, ``reversed``, ``next``, context entry (``__enter__`` /
116
+ ``__aenter__``), async iteration, and subclassing. Cheap structural probes stay silent — ordering comparisons,
117
+ ``format``, and context exit (``__exit__`` / ``__aexit__``) — mirroring the silent ``__eq__`` / ``__len__`` /
118
+ ``__str__``. In-place operators return the active object's own result, so a proxied value assigned via ``+=``
119
+ rebinds to that result rather than a re-wrapped proxy.
120
+
121
+ Known limitations:
122
+ **Structural ABC over-claim**: because dunder methods are installed unconditionally on the *type*
123
+ (implicit special-method lookup bypasses ``__getattr__`` and cannot be conditional per-instance),
124
+ ``isinstance(proxy, os.PathLike)`` returns ``True`` even when the wrapped object is not a path — then
125
+ ``os.fspath(proxy)`` raises ``TypeError``. The same applies to ``Awaitable``, ``AsyncIterable``, and
126
+ any other structural ABC that keys on dunder presence. Always check the *unwrapped* object's type
127
+ when using structural ABCs as a dispatch guard, or call ``type(deprecated_instance_proxy.__class__)``
128
+ to get the wrapped type (which is ``_DeprecatedProxy``).
129
+
130
+ """
131
+
132
+ @staticmethod
133
+ def _get_static_attr_owner(obj: Any) -> Any: # noqa: ANN401
134
+ """Return the object whose attributes should be validated without dynamic lookup.
135
+
136
+ For proxy targets, validate against the same "active" object attribute access will ultimately reach (callable
137
+ target when configured, otherwise the wrapped source).
138
+
139
+ Defensive cycle guard: stacked-proxy chains are linear in normal use (the frozen
140
+ :class:`~deprecate._types.DeprecationConfig` prevents reassignment of ``target`` after construction),
141
+ but the guard breaks the loop on the unlikely case of a circular chain so this helper never blocks.
142
+
143
+ """
144
+ seen: set[int] = set()
145
+ while isinstance(obj, _DeprecatedProxy):
146
+ if id(obj) in seen:
147
+ break
148
+ seen.add(id(obj))
149
+ dep = object.__getattribute__(obj, "__deprecated__")
150
+ cfg = object.__getattribute__(obj, "_DeprecatedProxy__config")
151
+ target = dep.target
152
+ obj = target if target is not None and not isinstance(target, TargetMode) else cfg.obj
153
+ return obj
154
+
155
+ @classmethod
156
+ def _has_static_attribute(cls, obj: Any, name: str) -> bool: # noqa: ANN401
157
+ """Return whether *name* exists without invoking ``__getattr__`` or descriptors."""
158
+ try:
159
+ inspect.getattr_static(cls._get_static_attr_owner(obj), name)
160
+ except AttributeError:
161
+ return False
162
+ return True
163
+
164
+ @staticmethod
165
+ def _target_display_name(target: Any, fallback: str) -> str: # noqa: ANN401
166
+ """Return a warning-display name without triggering proxy ``__getattr__``."""
167
+ target_owner = _DeprecatedProxy._get_static_attr_owner(target)
168
+ return getattr(target_owner, "__name__", fallback)
169
+
170
+ @staticmethod
171
+ def _validate_attrs_mapping(
172
+ attrs_mapping: dict[str, Optional[str]],
173
+ obj: Any, # noqa: ANN401
174
+ attr_check_obj: Any, # noqa: ANN401
175
+ ) -> None:
176
+ """Validate ``attrs_mapping`` at decoration time.
177
+
178
+ Runs three checks against the configured mapping:
179
+
180
+ 1. Reject true cycles in the redirect chain.
181
+ 2. Confirm every non-``None`` redirect target attribute exists on *attr_check_obj* so
182
+ accessing a deprecated alias never raises :class:`AttributeError` on the first warning.
183
+ 3. Confirm every warn-only key (``None`` value) exists on at least one of *attr_check_obj*
184
+ or *obj* — a key on neither would always raise :class:`AttributeError` on access.
185
+
186
+ Args:
187
+ attrs_mapping: The redirect map from deprecated attribute names to canonical names
188
+ (or ``None`` for warn-only).
189
+ obj: The wrapped source object — used as a fallback for warn-only key existence.
190
+ attr_check_obj: The class against which redirect targets are validated; the caller
191
+ pre-computes this from a concrete callable target, falling back to *obj* for
192
+ ``TargetMode`` values and legacy boolean sentinels.
193
+
194
+ Raises:
195
+ ValueError: If *attrs_mapping* contains a cycle, a missing redirect target, or a
196
+ warn-only key absent from both classes.
197
+
198
+ """
199
+ # Reject true cycles in ``attrs_mapping`` at decoration time. Non-cyclic chains are allowed at runtime
200
+ # and surfaced by audit as mapping chains.
201
+ cycle_starters: list[str] = []
202
+ for start in attrs_mapping:
203
+ visited: set[str] = {start}
204
+ current = attrs_mapping[start]
205
+ while current is not None and current in attrs_mapping:
206
+ if current in visited:
207
+ cycle_starters.append(start)
208
+ break
209
+ visited.add(current)
210
+ current = attrs_mapping[current]
211
+ if cycle_starters:
212
+ raise ValueError(
213
+ f"`attrs_mapping` has circular redirects — the redirect chain starting from"
214
+ f" {sorted(set(cycle_starters))} loops back to a previously visited key."
215
+ " Redirect chains must terminate at an attribute name that does not loop."
216
+ )
217
+ _DeprecatedProxy._validate_attrs_redirect_targets(attrs_mapping, attr_check_obj)
218
+ _DeprecatedProxy._validate_attrs_warn_only_keys(attrs_mapping, obj, attr_check_obj)
219
+
220
+ @staticmethod
221
+ def _validate_attrs_redirect_targets(
222
+ attrs_mapping: dict[str, Optional[str]],
223
+ attr_check_obj: Any, # noqa: ANN401
224
+ ) -> None:
225
+ """Validate that every non-``None`` redirect target attribute exists on the class.
226
+
227
+ Ensures that accessing a deprecated alias never raises :class:`AttributeError` on the
228
+ first warning — every redirect target must resolve to an existing attribute on
229
+ *attr_check_obj* at decoration time.
230
+
231
+ Args:
232
+ attrs_mapping: The redirect map from deprecated attribute names to canonical names
233
+ (or ``None`` for warn-only).
234
+ attr_check_obj: The class against which non-``None`` redirect targets are validated.
235
+
236
+ Raises:
237
+ ValueError: If any non-``None`` redirect target is absent from *attr_check_obj*.
238
+
239
+ """
240
+ # For @dataclass targets, required fields (no default) are not visible via getattr_static
241
+ # because they have no class-level value — but they DO exist as valid constructor params
242
+ # and instance attributes. Check __dataclass_fields__ as a fallback.
243
+ _owner = _DeprecatedProxy._get_static_attr_owner(attr_check_obj)
244
+ _dc_field_names: set[str] = set(getattr(_owner, "__dataclass_fields__", {}))
245
+ _resolved_targets = list(attrs_mapping.items())
246
+ missing_targets = [
247
+ f"{k!r} -> {target!r}"
248
+ for k, target in _resolved_targets
249
+ if target is not None
250
+ and not _DeprecatedProxy._has_static_attribute(attr_check_obj, target)
251
+ and target not in _dc_field_names
252
+ ]
253
+ if missing_targets:
254
+ raise ValueError(
255
+ f"`attrs_mapping` redirect targets not found on the active class: {missing_targets}."
256
+ " Each non-None value must be an existing attribute name on the target class when `target` is"
257
+ " provided, or on the wrapped class otherwise."
258
+ )
259
+
260
+ @staticmethod
261
+ def _validate_attrs_warn_only_keys(
262
+ attrs_mapping: dict[str, Optional[str]],
263
+ obj: Any, # noqa: ANN401
264
+ attr_check_obj: Any, # noqa: ANN401
265
+ ) -> None:
266
+ """Validate that every warn-only key (``None``-value entry) exists on at least one class.
267
+
268
+ A ``None`` redirect means "warn but still serve the attribute value" — the attribute can
269
+ live on the target (same-name warning: kept in new API) or only on the source
270
+ (being-removed attribute that falls back to the source value in ``__getattr__``). Raise
271
+ only when absent from both classes; a key on neither would always raise
272
+ :class:`AttributeError` on access.
273
+
274
+ Args:
275
+ attrs_mapping: The redirect map from deprecated attribute names to canonical names
276
+ (or ``None`` for warn-only).
277
+ obj: The wrapped source object — used as a fallback for warn-only key existence.
278
+ attr_check_obj: The class against which warn-only keys are first checked before
279
+ falling back to *obj*.
280
+
281
+ Raises:
282
+ ValueError: If any warn-only key is absent from both *attr_check_obj* and *obj*.
283
+
284
+ """
285
+ missing_keys = [
286
+ k
287
+ for k, v in attrs_mapping.items()
288
+ if v is None
289
+ and not _DeprecatedProxy._has_static_attribute(attr_check_obj, k)
290
+ and not _DeprecatedProxy._has_static_attribute(obj, k)
291
+ ]
292
+ if missing_keys:
293
+ raise ValueError(
294
+ f"`attrs_mapping` warn-only keys not found on either class: {missing_keys}."
295
+ " Each key with a `None` value must be an existing attribute name on the target class"
296
+ " when `target` is provided, or on the wrapped class."
297
+ )
298
+
299
+ def __init__(
300
+ self,
301
+ obj: Any, # noqa: ANN401
302
+ name: str,
303
+ *,
304
+ target: Any = None, # noqa: ANN401
305
+ args_mapping: Optional[dict[str, Optional[str]]] = None,
306
+ args_extra: Optional[dict[str, Any]] = None,
307
+ attrs_mapping: Optional[dict[str, Optional[str]]] = None,
308
+ deprecated_in: str = "",
309
+ remove_in: str = "",
310
+ num_warns: int = 1,
311
+ stream: Optional[Callable[..., None]] = deprecation_warning,
312
+ template_mgs: Optional[str] = None,
313
+ read_only: bool = False,
314
+ docstring_style: str = "auto",
315
+ _misconfigured_override: bool = False,
316
+ ) -> None:
317
+ """Initialise the proxy with typed runtime/config dataclasses.
318
+
319
+ ``__config`` stores private mutable runtime state in :class:`~deprecate._types._ProxyConfig` (obj, stream,
320
+ num_warns, read_only, args_extra, warned counter).
321
+
322
+ ``__deprecated__`` is the public metadata interface consumed by audit tools
323
+ (:func:`~deprecate.audit.validate_deprecation_wrapper`,
324
+ :func:`~deprecate.audit.find_deprecation_wrappers`, etc.)
325
+ as a :class:`~deprecate._types.DeprecationConfig` instance aligned with the ``@deprecated`` schema.
326
+
327
+ ``_misconfigured_override`` is a private hook used by :func:`~deprecate.deprecated` when it delegates to
328
+ :func:`~deprecate.deprecated_class` for class targets: it lets the caller pre-compute misconfig signals
329
+ (raw ``target=False`` plus NOTIFY+args_mapping / NOTIFY+args_extra detected upstream) before the proxy
330
+ rewrites them away, so the final frozen :class:`~deprecate._types.DeprecationConfig` records every signal
331
+ in one place.
332
+
333
+ """
334
+ # Probe ``template_mgs`` against every documented placeholder so typos and malformed conversion specifiers
335
+ # fail at decoration time instead of on the first proxy access.
336
+ _validate_template_mgs(template_mgs)
337
+ # Reject true cycles in ``attrs_mapping`` at decoration time. Non-cyclic chains are allowed at runtime
338
+ # and surfaced by audit as mapping chains.
339
+ if attrs_mapping is not None:
340
+ attr_check_obj = target if target is not None and not isinstance(target, (TargetMode, bool)) else obj
341
+ self._validate_attrs_mapping(attrs_mapping, obj, attr_check_obj)
342
+ # Track whether the raw ``target=False`` sentinel was passed so audit can flag it. The override
343
+ # path lets upstream callers fold their own pre-validated misconfig signals into the same flag.
344
+ misconfigured = target is False or _misconfigured_override
345
+ if isinstance(target, bool):
346
+ target = TargetMode._from_legacy_proxy(target, args_mapping=args_mapping, stacklevel=3)
347
+ _dc_check = _DeprecatedProxy._get_static_attr_owner(
348
+ target if target is not None and not isinstance(target, (TargetMode, bool)) else obj
349
+ )
350
+ if args_mapping is not None:
351
+ args_mapping = dict(args_mapping)
352
+ # Copy ``attrs_mapping`` too (``args_mapping`` is copied just above): the frozen config stores it, so
353
+ # aliasing the caller's dict would let post-decoration mutation introduce the exact cycle validation rejected.
354
+ if attrs_mapping is not None:
355
+ attrs_mapping = dict(attrs_mapping)
356
+ # Dataclass dual-surface auto-expand: copy attrs_mapping entries that name a dataclass field
357
+ # into args_mapping so both attribute access and constructor kwarg paths emit a FutureWarning.
358
+ args_mapping, _auto_expanded = _expand_dc_attrs_to_args(_dc_check, attrs_mapping, args_mapping)
359
+ # When auto-expand produced a non-empty args_mapping and the user provided no explicit
360
+ # target, set target = obj so the callable-target + both-mappings path activates both surfaces.
361
+ if _auto_expanded and target is None:
362
+ target = obj
363
+ # Kwargs-compatibility guard: detect args_mapping keys that remap to POSITIONAL_ONLY params.
364
+ _incompatible = _detect_proxy_positional_only(_dc_check, name, args_mapping)
365
+ # Constructor POSITIONAL_ONLY split data: the call path forwards remapped values
366
+ # positionally (same split machinery as the @deprecated dispatcher) instead of the
367
+ # historical pop-and-setattr fallback, which failed for required params, immutable
368
+ # instances, and constructor-derived state.
369
+ _ctor_positional_only, _ctor_positional_only_order = _detect_ctor_positional_only(_dc_check)
370
+ # Auto-resolve: no explicit target but args_mapping provided → ARGS_REMAP
371
+ if target is None and args_mapping:
372
+ target = TargetMode.ARGS_REMAP
373
+ # Auto-resolve: no explicit target but attrs_mapping provided → ATTRS_REMAP
374
+ # Mirrors the args_mapping auto-resolve above: presence of the dict is the activation
375
+ # signal; explicit TargetMode.ATTRS_REMAP is the equivalent self-documenting form.
376
+ if target is None and attrs_mapping:
377
+ target = TargetMode.ATTRS_REMAP
378
+ # Validate misconfig (NOTIFY+args_mapping, ARGS_REMAP+no-args_mapping, NOTIFY+args_extra). The
379
+ # validator returns True when any signal fired so we extend ``misconfigured`` accordingly —
380
+ # ``DeprecationConfig.misconfigured`` becomes a single source of truth for all four signals.
381
+ if isinstance(target, TargetMode):
382
+ misconfigured |= TargetMode._validate(
383
+ target, name, args_mapping=args_mapping, args_extra=args_extra, stacklevel=4
384
+ )
385
+ # Proxy-specific validation: attrs_mapping combinations not covered by _validate().
386
+ # stacklevel=4: caller → decorator(cls) → __init__ → _validate_proxy → warn
387
+ # deprecated_class() itself is already off the stack when decorator(cls) runs.
388
+ misconfigured |= TargetMode._validate_proxy(
389
+ target,
390
+ name,
391
+ attrs_mapping=attrs_mapping,
392
+ args_mapping=args_mapping,
393
+ args_extra=args_extra,
394
+ stacklevel=4,
395
+ )
396
+ # Private mutable runtime state — warn counter, stream, read-only flag, wrapped object, extras to merge
397
+ # after args_mapping at call time, optional custom warning template.
398
+ cfg = _ProxyConfig(
399
+ obj=obj,
400
+ stream=stream,
401
+ num_warns=num_warns,
402
+ read_only=read_only,
403
+ args_extra=args_extra,
404
+ template_mgs=template_mgs,
405
+ attrs_mapping=attrs_mapping,
406
+ )
407
+ object.__setattr__(self, "_DeprecatedProxy__config", cfg)
408
+ # Static deprecation metadata stored as a dunder attribute — readable by audit tools via __deprecated__.
409
+ dep_meta = DeprecationConfig(
410
+ deprecated_in=deprecated_in,
411
+ remove_in=remove_in,
412
+ name=name,
413
+ target=target,
414
+ args_mapping=args_mapping,
415
+ args_extra=args_extra,
416
+ misconfigured=misconfigured,
417
+ docstring_style=normalize_docstring_style(docstring_style),
418
+ template_mgs=template_mgs,
419
+ attrs_mapping=attrs_mapping,
420
+ args_mapping_auto_expanded=tuple(_auto_expanded),
421
+ args_mapping_positional_only=_incompatible,
422
+ target_positional_only=_ctor_positional_only,
423
+ target_positional_only_order=_ctor_positional_only_order,
424
+ )
425
+ object.__setattr__(self, "__deprecated__", dep_meta)
426
+ # Expose the wrapped object's docstring as an instance attribute so that external tools (autodoc,
427
+ # mkdocstrings/griffe) see the source class's documentation rather than _DeprecatedProxy's own class docstring.
428
+ _doc = getattr(obj, "__doc__", None)
429
+ if _doc:
430
+ object.__setattr__(self, "__doc__", _doc)
431
+
432
+ # ------------------------------------------------------------------
433
+ # Internal helpers — must use object.__getattribute__ / object.__setattr__
434
+ # to avoid triggering the proxy's own __getattr__ / __setattr__.
435
+ # ------------------------------------------------------------------
436
+
437
+ @property
438
+ def _cfg(self) -> _ProxyConfig:
439
+ """Private mutable runtime state (warn counter, stream, read-only flag, wrapped object).
440
+
441
+ Private to this class — not part of the public API and not consumed by audit tools.
442
+
443
+ """
444
+ return cast(_ProxyConfig, object.__getattribute__(self, "_DeprecatedProxy__config"))
445
+
446
+ @property
447
+ def _dep(self) -> DeprecationConfig:
448
+ """Static deprecation metadata (versions, name, target, args_mapping).
449
+
450
+ Stored as ``__deprecated__`` (dunder, not name-mangled) — audit tools and external code may read it directly;
451
+ this property simply provides a typed view of the same object.
452
+
453
+ """
454
+ return cast(DeprecationConfig, object.__getattribute__(self, "__deprecated__"))
455
+
456
+ def _build_attr_warning_msg(
457
+ self,
458
+ arg_name: str,
459
+ dep: DeprecationConfig,
460
+ attrs_mapping: dict[str, Optional[str]],
461
+ target: Any, # noqa: ANN401
462
+ custom_template: Optional[str],
463
+ ) -> Optional[str]:
464
+ """Build the warning message for a deprecated ``attrs_mapping`` attribute access.
465
+
466
+ Strips the ``"__attr__:"`` prefix from *arg_name* to recover the attribute name visible to
467
+ callers. The prefix must be preserved in the *arg_name* passed by the caller so that the
468
+ per-attribute budget key in ``cfg.warned_args`` stays disjoint from any same-named
469
+ ``args_mapping`` key — this method intentionally does not reassign *arg_name*.
470
+
471
+ Returns:
472
+ The formatted warning string, or ``None`` when *attr_name* is not registered in
473
+ ``dep.attrs_mapping`` (caller should silently return without warning).
474
+
475
+ """
476
+ attr_name = arg_name[len("__attr__:") :]
477
+ if attr_name not in attrs_mapping:
478
+ return None
479
+ new_attr = attrs_mapping[attr_name]
480
+ if new_attr is not None:
481
+ owner = self._target_display_name(target, dep.name) if not isinstance(target, TargetMode) else dep.name
482
+ target_path = f"{owner}.{new_attr}"
483
+ template = custom_template or TEMPLATE_WARNING_CALLABLE
484
+ return template % {
485
+ "source_name": attr_name,
486
+ "source_path": attr_name,
487
+ "deprecated_in": dep.deprecated_in,
488
+ "remove_in": dep.remove_in,
489
+ "target_name": new_attr,
490
+ "target_path": target_path,
491
+ "argument_map": "",
492
+ }
493
+ template = custom_template or TEMPLATE_WARNING_NO_TARGET
494
+ return template % {
495
+ "source_name": attr_name,
496
+ "source_path": attr_name,
497
+ "deprecated_in": dep.deprecated_in,
498
+ "remove_in": dep.remove_in,
499
+ "target_name": "",
500
+ "target_path": "",
501
+ "argument_map": "",
502
+ }
503
+
504
+ def _warn(self, *, arg_name: Optional[str] = None, _extra_frames: int = 0) -> None:
505
+ """Emit a deprecation warning if the warn budget is not exhausted.
506
+
507
+ Args:
508
+ arg_name: When given, use per-argument warning tracking (``cfg.warned_args``) instead of the global
509
+ ``cfg.warned`` counter. The warning is suppressed when the per-argument count has already reached
510
+ ``cfg.num_warns``. When provided alongside an ``args_mapping`` entry, the emitted message uses the
511
+ per-argument template (`old -> new`) rather than the generic callable template — matching the
512
+ decorator's argument-deprecation form.
513
+ _extra_frames: Additional Python helper frames between the public accessor and ``_warn``.
514
+
515
+ """
516
+ cfg = self._cfg
517
+ stream = cfg.stream
518
+ if not stream:
519
+ return
520
+ # Build the message before taking the lock: attrs_mapping miss returns None (no warning),
521
+ # and message building is pure CPU work with no IO.
522
+ dep = self._dep
523
+ msg = _build_proxy_warn_msg(self, arg_name, dep, cfg)
524
+ if msg is None:
525
+ return
526
+ # Take the state lock around quota check + counter increment so concurrent first accesses
527
+ # cannot all read the counter as 0, all pass the gate, and each emit a warning
528
+ # (check-then-act race). Mirrors the decorator-path pattern in ``deprecation.py``:
529
+ # decide-and-increment under the lock, emit the warning outside to avoid serialising
530
+ # callers on a potentially slow ``stream`` callable.
531
+ should_warn = False
532
+ with cfg.lock:
533
+ if arg_name is not None:
534
+ arg_count = cfg.warned_args.get(arg_name, 0)
535
+ if cfg.num_warns < 0 or arg_count < cfg.num_warns:
536
+ should_warn = True
537
+ cfg.warned_args[arg_name] = arg_count + 1
538
+ else:
539
+ if cfg.num_warns < 0 or cfg.warned < cfg.num_warns:
540
+ should_warn = True
541
+ cfg.warned += 1
542
+ if not should_warn:
543
+ return
544
+ # Route the warning to the caller's frame rather than ``proxy.py``.
545
+ # A plain ``try/except TypeError`` would swallow a TypeError raised *inside* a
546
+ # stacklevel-accepting stream and re-invoke it (double side-effect).
547
+ # Checking the exception message distinguishes a keyword-rejection error from an
548
+ # internal one — the stream is called exactly once in all but the keyword-rejection case.
549
+ try:
550
+ stream(msg, stacklevel=_DEFAULT_STACKLEVEL_TO_CALLER + _extra_frames)
551
+ except TypeError as _exc:
552
+ if "stacklevel" in str(_exc) or "keyword" in str(_exc):
553
+ stream(msg)
554
+ else:
555
+ raise
556
+
557
+ def _check_read_only(self, operation: str) -> None:
558
+ """Raise AttributeError when the proxy is in read-only mode.
559
+
560
+ Raises:
561
+ AttributeError: If ``read_only=True`` was set at construction time.
562
+
563
+ """
564
+ if self._cfg.read_only:
565
+ name: str = self._dep.name
566
+ raise AttributeError(
567
+ f"'{name}' is deprecated and read-only. {operation} is not allowed. Migrate away from this object."
568
+ )
569
+
570
+ @property
571
+ def wrapped(self) -> Any: # noqa: ANN401
572
+ """The deprecated source object this proxy wraps (audit contract accessor)."""
573
+ return self._cfg.obj
574
+
575
+ def _get_active(self) -> Any: # noqa: ANN401
576
+ """Return the active object: *target* when set, otherwise *source*."""
577
+ target = self._dep.target
578
+ if target is not None and not isinstance(target, TargetMode):
579
+ return target
580
+ return self._cfg.obj
581
+
582
+ def _apply_args_mapping(self, kwargs: dict[str, Any]) -> dict[str, Any]:
583
+ """Apply args_mapping to *kwargs*, renaming or dropping keys as configured.
584
+
585
+ When both the old key and its mapped new-name key are present in *kwargs*, the explicit new-name value wins over
586
+ the renamed old-name value.
587
+
588
+ """
589
+ args_mapping = self._dep.args_mapping
590
+ if not args_mapping or not kwargs:
591
+ return kwargs
592
+ args_to_drop = {k for k, v in args_mapping.items() if v is None}
593
+ # caller → __call__ → _proxy_call_* → _apply_args_mapping → _apply_args_mapping_collisions → warn = stacklevel 5
594
+ explicit_new = _apply_args_mapping_collisions(
595
+ args_mapping, kwargs, args_to_drop, self._dep.name, self._cfg.stream, stacklevel=5
596
+ )
597
+ result = {(args_mapping.get(k) or k): v for k, v in kwargs.items() if k not in args_to_drop}
598
+ result.update(explicit_new)
599
+ return result
600
+
601
+ def _merge_args_extra(self, kwargs: dict[str, Any]) -> dict[str, Any]:
602
+ """Merge :attr:`_ProxyConfig.args_extra` into *kwargs*; extra values win."""
603
+ args_extra = self._cfg.args_extra
604
+ if not args_extra:
605
+ return kwargs
606
+ merged = dict(kwargs)
607
+ merged.update(args_extra)
608
+ return merged
609
+
610
+ @staticmethod
611
+ def _is_potential_mutator(name: str) -> bool:
612
+ """Heuristic to detect common mutating methods on built-in collections.
613
+
614
+ This is intentionally conservative and only covers the most common mutating APIs on built-in container types
615
+ (lists, dicts, sets).
616
+
617
+ """
618
+ mutating_names = {
619
+ "append",
620
+ "extend",
621
+ "insert",
622
+ "pop",
623
+ "remove",
624
+ "clear",
625
+ "update",
626
+ "setdefault",
627
+ "add",
628
+ "discard",
629
+ }
630
+ return name in mutating_names
631
+
632
+ def _guard_read_only_mutator(self, attr: Any, name: str) -> Any: # noqa: ANN401
633
+ """Return a guarded callable for standard mutators in read-only mode."""
634
+ if self._cfg.read_only and callable(attr) and self._is_potential_mutator(name):
635
+
636
+ def _guarded_mutator(*args: Any, **kwargs: Any) -> None: # noqa: ANN401
637
+ """Raise a read-only error when this mutating method is called."""
638
+ self._check_read_only(f"Calling mutating method '{name}'")
639
+
640
+ return _guarded_mutator
641
+ return attr
642
+
643
+ # ------------------------------------------------------------------
644
+ # Attribute access
645
+ # ------------------------------------------------------------------
646
+
647
+ def __getattr__(self, name: str) -> Any: # noqa: ANN401
648
+ """Forward attribute lookup to the active object, emitting a deprecation warning.
649
+
650
+ When ``attrs_mapping`` is configured, only attributes listed in the mapping emit a warning; all other accesses
651
+ are forwarded silently without a warning. The redirect target name (value in the mapping) is used for the
652
+ actual attribute lookup when the value is a non-``None`` string; ``None`` means warn-only with no rename on the
653
+ active object.
654
+
655
+ Without ``attrs_mapping``, the attribute is resolved *first* and the warning fires only on successful access —
656
+ failed introspection probes (``hasattr`` duck-typing, copy/pickle machinery) raise :class:`AttributeError`
657
+ without warning or consuming the warn budget. Dunder reads (``__mro__``, ``__wrapped__``, …) are forwarded
658
+ silently: they are introspection machinery, not a use of the deprecated API — the same rationale as
659
+ :meth:`~deprecate.proxy._DeprecatedProxy.__instancecheck__`.
660
+
661
+ In read-only mode, common mutating methods on built-in collections (for example, ``append`` or ``update``) are
662
+ wrapped so that calling them raises :class:`AttributeError` instead of mutating the underlying object.
663
+
664
+ """
665
+ # Half-initialised instance guard (``cls.__new__(cls)`` during copy/pickle reconstruction): the ``_cfg``
666
+ # property raises AttributeError when ``__config`` is missing, which Python routes back into __getattr__ —
667
+ # touching ``self._cfg`` here again would mutually recurse (property ↔ __getattr__) into RecursionError.
668
+ try:
669
+ cfg = cast(_ProxyConfig, object.__getattribute__(self, "_DeprecatedProxy__config"))
670
+ except AttributeError:
671
+ raise AttributeError(name) from None
672
+ attrs_mapping = cfg.attrs_mapping
673
+ if attrs_mapping is not None:
674
+ if name in attrs_mapping:
675
+ self._warn(arg_name=f"__attr__:{name}")
676
+ redirect = attrs_mapping[name]
677
+ active = self._get_active()
678
+ attr_name = redirect if redirect is not None else name
679
+ if redirect is None:
680
+ try:
681
+ attr = getattr(active, attr_name)
682
+ except AttributeError:
683
+ # Attribute absent from target — fall back to source. Covers the "being-removed" pattern where
684
+ # the deprecated attribute still lives on the old class but was dropped from the new target.
685
+ attr = getattr(cfg.obj, attr_name)
686
+ return self._guard_read_only_mutator(attr, attr_name)
687
+ attr = getattr(active, attr_name)
688
+ return self._guard_read_only_mutator(attr, attr_name)
689
+ # Not a deprecated attr — silent passthrough, no warning.
690
+ attr = getattr(self._get_active(), name)
691
+ return self._guard_read_only_mutator(attr, name)
692
+ # Resolve first so a missing attribute raises without warning or burning the warn budget.
693
+ attr = getattr(self._get_active(), name)
694
+ # ARGS_REMAP deprecates constructor argument names only; attribute access is unrelated
695
+ # to the deprecated call signature and must not emit a spurious global warning.
696
+ # Dunder reads are silent machinery — see the docstring above.
697
+ if self._dep.target is not TargetMode.ARGS_REMAP and not _is_dunder(name):
698
+ self._warn()
699
+ return self._guard_read_only_mutator(attr, name)
700
+
701
+ def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401
702
+ """Forward attribute mutation to the active object, raising in read-only mode.
703
+
704
+ When ``attrs_mapping`` is configured and the attribute name is a deprecated alias, emits a warning and
705
+ redirects the write to the canonical attribute name.
706
+
707
+ Raises:
708
+ AttributeError: If the proxy is in read-only mode.
709
+
710
+ """
711
+ self._check_read_only(f"Setting attribute '{name}'")
712
+ attrs_mapping = self._cfg.attrs_mapping
713
+ if attrs_mapping is not None and name in attrs_mapping:
714
+ self._warn(arg_name=f"__attr__:{name}")
715
+ redirect = attrs_mapping[name]
716
+ active = self._get_active()
717
+ attr_name = redirect if redirect is not None else name
718
+ if redirect is None:
719
+ # "Being-removed" pattern: attribute may live only on the source class.
720
+ # Mirror the __getattr__ fallback: prefer active, fall back to source.
721
+ owner = active if hasattr(active, attr_name) else self._cfg.obj
722
+ setattr(owner, attr_name, value)
723
+ return
724
+ setattr(active, attr_name, value)
725
+ return
726
+ setattr(self._get_active(), name, value)
727
+
728
+ def __delattr__(self, name: str) -> None:
729
+ """Forward attribute deletion to the active object, raising in read-only mode.
730
+
731
+ When ``attrs_mapping`` is configured and the attribute name is a deprecated alias, emits a warning and
732
+ redirects the deletion to the canonical attribute name.
733
+
734
+ Raises:
735
+ AttributeError: If the proxy is in read-only mode.
736
+
737
+ """
738
+ self._check_read_only(f"Deleting attribute '{name}'")
739
+ attrs_mapping = self._cfg.attrs_mapping
740
+ if attrs_mapping is not None and name in attrs_mapping:
741
+ self._warn(arg_name=f"__attr__:{name}")
742
+ redirect = attrs_mapping[name]
743
+ active = self._get_active()
744
+ attr_name = redirect if redirect is not None else name
745
+ if redirect is None:
746
+ # "Being-removed" pattern: attribute may live only on the source class.
747
+ # Mirror the __getattr__ fallback so delete behaviour is symmetric.
748
+ try:
749
+ delattr(active, attr_name)
750
+ except AttributeError:
751
+ delattr(self._cfg.obj, attr_name)
752
+ return
753
+ delattr(active, attr_name)
754
+ return
755
+ delattr(self._get_active(), name)
756
+
757
+ # ------------------------------------------------------------------
758
+ # Subscript access
759
+ # ------------------------------------------------------------------
760
+
761
+ def __getitem__(self, key: Any) -> Any: # noqa: ANN401
762
+ """Forward subscript lookup to the active object, emitting a deprecation warning."""
763
+ self._warn()
764
+ return self._get_active()[key]
765
+
766
+ def __setitem__(self, key: Any, value: Any) -> None: # noqa: ANN401
767
+ """Forward subscript mutation to the active object, raising in read-only mode.
768
+
769
+ Raises:
770
+ AttributeError: If the proxy is in read-only mode.
771
+
772
+ """
773
+ self._check_read_only(f"Setting item '{key}'")
774
+ self._get_active()[key] = value
775
+
776
+ def __delitem__(self, key: Any) -> None: # noqa: ANN401
777
+ """Forward subscript deletion to the active object, raising in read-only mode.
778
+
779
+ Raises:
780
+ AttributeError: If the proxy is in read-only mode.
781
+
782
+ """
783
+ self._check_read_only(f"Deleting item '{key}'")
784
+ del self._get_active()[key]
785
+
786
+ # ------------------------------------------------------------------
787
+ # Container protocol
788
+ # ------------------------------------------------------------------
789
+
790
+ def __len__(self) -> int:
791
+ """Return length of the active object without emitting a warning."""
792
+ return len(self._get_active())
793
+
794
+ def __iter__(self) -> Iterator[Any]:
795
+ """Iterate over the active object, emitting a deprecation warning."""
796
+ self._warn()
797
+ return iter(self._get_active())
798
+
799
+ def __contains__(self, item: Any) -> bool: # noqa: ANN401
800
+ """Check membership in the active object without emitting a warning."""
801
+ return item in self._get_active()
802
+
803
+ # ------------------------------------------------------------------
804
+ # Callable protocol
805
+ # ------------------------------------------------------------------
806
+
807
+ def __call__(self, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401
808
+ """Call the active object, emitting a deprecation warning conditionally based on target mode.
809
+
810
+ Branching logic:
811
+ - :attr:`~deprecate._types.TargetMode.ARGS_REMAP`: warn only when a deprecated kwarg name is present in the
812
+ call; remap, merge ``args_extra``, and call ``obj``.
813
+ - Callable target with ``args_mapping``: warn per deprecated kwarg present; if none of the old names were
814
+ passed still warn at the callable level (class is deprecated); remap, merge ``args_extra``, and forward to
815
+ target.
816
+ - Callable target without ``args_mapping``: warn (global budget), merge ``args_extra``, and forward to target.
817
+ - :attr:`~deprecate._types.TargetMode.ATTRS_REMAP`: governs attribute access only; ``args_extra`` is
818
+ intentionally not applied on ``__call__`` — :meth:`~deprecate._types.TargetMode._validate_proxy`
819
+ already warns about this misconfiguration at decoration time.
820
+ - :attr:`~deprecate._types.TargetMode.NOTIFY`: always warn (global budget) and forward kwargs unchanged;
821
+ ``args_extra`` is intentionally ignored (misconfig).
822
+
823
+ """
824
+ dep = object.__getattribute__(self, "__deprecated__")
825
+ cfg = object.__getattribute__(self, "_DeprecatedProxy__config")
826
+
827
+ # ATTRS_REMAP stacked over a proxy: delegate the call to the inner proxy without firing the global
828
+ # callable warning. ATTRS_REMAP governs attribute access only; the call itself is not a deprecated
829
+ # surface, so forwarding through the inner proxy avoids double-warning when both layers are active.
830
+ if dep.target is TargetMode.ATTRS_REMAP and isinstance(cfg.obj, _DeprecatedProxy):
831
+ return cfg.obj(*args, **kwargs)
832
+ # ATTRS_REMAP (non-stacking path): only the listed attribute aliases are deprecated, so
833
+ # instantiating/calling the class is not a deprecated surface — forward WITHOUT the global
834
+ # warning (mirrors the stacked branch above and the ARGS_REMAP skip in __getattr__). Moving
835
+ # this check above ``self._warn()`` keeps plain construction from branding the whole class
836
+ # deprecated and burning the global warn budget. args_extra is intentionally not applied —
837
+ # validated as a misconfiguration at decoration time.
838
+ if dep.target is TargetMode.ATTRS_REMAP:
839
+ return self._get_active()(*args, **kwargs)
840
+ if dep.target is TargetMode.ARGS_REMAP:
841
+ return _proxy_call_args_remap(self, dep, cfg, args, kwargs)
842
+ if callable(dep.target) and dep.args_mapping:
843
+ return _proxy_call_callable_with_mapping(self, dep, dep.target, args, kwargs)
844
+ # Callable target without args_mapping: warn globally; still merge args_extra so
845
+ # injected defaults reach the target.
846
+ self._warn()
847
+ if callable(dep.target):
848
+ return dep.target(*args, **self._merge_args_extra(kwargs))
849
+ # NOTIFY: forward unchanged — args_extra is intentionally ignored (already warned at construction).
850
+ if dep.target is TargetMode.NOTIFY:
851
+ return self._get_active()(*args, **kwargs)
852
+ # No target configured (e.g. deprecated_instance with no target): merge args_extra into the call so
853
+ # wrappers can inject default kwargs even without a forwarding target.
854
+ return self._get_active()(*args, **self._merge_args_extra(kwargs))
855
+
856
+ # ------------------------------------------------------------------
857
+ # Comparison and hashing
858
+ # ------------------------------------------------------------------
859
+
860
+ def __eq__(self, other: object) -> bool:
861
+ """Compare the *active* object for equality — the object the proxy actually serves.
862
+
863
+ Data access (attribute/item/call) forwards to the active object (target when set, else source), so identity #
864
+ operations must too; comparing the source while serving the target would make a # target-forwarding proxy equal
865
+ to an object it never returns.
866
+
867
+ """
868
+ obj = self._get_active()
869
+ if isinstance(other, _DeprecatedProxy):
870
+ other = other._get_active()
871
+ return bool(obj == other)
872
+
873
+ def __ne__(self, other: object) -> bool:
874
+ """Return the inverse of equality."""
875
+ return not self.__eq__(other)
876
+
877
+ def __hash__(self) -> int:
878
+ """Return the hash of the active object (consistent with :meth:`__eq__`)."""
879
+ return hash(self._get_active())
880
+
881
+ # ------------------------------------------------------------------
882
+ # String representations — no warning emitted (used for debugging)
883
+ # ------------------------------------------------------------------
884
+
885
+ def __repr__(self) -> str:
886
+ """Return repr of the active object (the object the proxy serves)."""
887
+ return repr(self._get_active())
888
+
889
+ def __str__(self) -> str:
890
+ """Return str of the active object (the object the proxy serves)."""
891
+ return str(self._get_active())
892
+
893
+ def __bool__(self) -> bool:
894
+ """Return bool of the active object without emitting a warning."""
895
+ return bool(self._get_active())
896
+
897
+ # ------------------------------------------------------------------
898
+ # Copy / pickle protocol — no warning emitted (structural machinery)
899
+ #
900
+ # Semantics: a copy (shallow, deep, or pickle round-trip) is a *proxy again* — the
901
+ # deprecation travels with the object so a copied deprecated config keeps warning during
902
+ # the migration window. The wrapped object is copied per the respective protocol; the
903
+ # frozen DeprecationConfig metadata is preserved; the warn-budget counters are snapshotted.
904
+ # ------------------------------------------------------------------
905
+
906
+ def __copy__(self) -> "_DeprecatedProxy":
907
+ """Return a new proxy wrapping a shallow copy of the wrapped object.
908
+
909
+ Deprecation metadata (frozen, immutable) is shared; the mutable warn-budget counters are snapshotted into an
910
+ independent config so the copy warns independently from the original.
911
+
912
+ """
913
+ cfg = self._cfg
914
+ new_cfg = replace(cfg, obj=copy.copy(cfg.obj), warned_args=dict(cfg.warned_args), lock=threading.Lock())
915
+ return _reconstruct_proxy(new_cfg, self._dep, object.__getattribute__(self, "__dict__").get("__doc__"))
916
+
917
+ def __deepcopy__(self, memo: dict[int, Any]) -> "_DeprecatedProxy":
918
+ """Return a new proxy deep-copying the wrapped object (and any instance target).
919
+
920
+ Registers the new proxy in *memo* before descending so self-referential structures that contain the proxy deep-
921
+ copy without infinite recursion.
922
+
923
+ """
924
+ cls = type(self)
925
+ new = cls.__new__(cls)
926
+ memo[id(self)] = new
927
+ object.__setattr__(new, "_DeprecatedProxy__config", copy.deepcopy(self._cfg, memo))
928
+ object.__setattr__(new, "__deprecated__", copy.deepcopy(self._dep, memo))
929
+ doc = object.__getattribute__(self, "__dict__").get("__doc__")
930
+ if doc is not None:
931
+ object.__setattr__(new, "__doc__", doc)
932
+ return new
933
+
934
+ def __reduce_ex__(self, protocol: SupportsIndex) -> tuple[Any, ...]:
935
+ """Support pickling: reconstruct the proxy from its two config dataclasses.
936
+
937
+ The default ``object.__reduce_ex__`` probes attributes through ``__getattr__`` and cannot
938
+ rebuild an instance whose state lives behind ``object.__setattr__``; this override pickles
939
+ the runtime config and frozen metadata directly and rebuilds via
940
+ :func:`~deprecate.proxy._reconstruct_proxy` without re-running ``__init__`` validation.
941
+
942
+ Note:
943
+ The ``stream`` callable is pickled by reference; lambdas and closures are not picklable
944
+ by the standard pickle protocol. Use a module-level callable (e.g. ``warnings.warn``)
945
+ or ``None`` when you intend to pickle the proxy.
946
+
947
+ For :func:`~deprecate.proxy.deprecated_instance` proxies the wrapped object is serialised
948
+ directly and pickle works reliably. For :func:`~deprecate.proxy.deprecated_class` proxies
949
+ the wrapped class is serialised by reference; if the module-level name was replaced by the
950
+ proxy (the typical usage), pickle cannot resolve the reference and raises
951
+ :class:`~pickle.PicklingError`.
952
+
953
+ """
954
+ doc = object.__getattribute__(self, "__dict__").get("__doc__")
955
+ return (_reconstruct_proxy, (self._cfg, self._dep, doc))
956
+
957
+ # ------------------------------------------------------------------
958
+ # Type protocol — supports isinstance/issubclass against a proxy
959
+ # ------------------------------------------------------------------
960
+
961
+ @property # type: ignore[misc]
962
+ def __class__(self) -> type:
963
+ """Report the active object's class so ``isinstance(proxy, WrappedType)`` holds.
964
+
965
+ Instance-side type transparency (the ``wrapt``/``unittest.mock`` technique): ``isinstance``
966
+ honours ``__class__``, so consumer code type-checking the deprecated object (json encoders,
967
+ validators, defensive ``isinstance``) behaves identically before and after wrapping.
968
+ Stacked proxy chains are resolved to the innermost concrete object. ``type(proxy)`` still
969
+ returns :class:`_DeprecatedProxy` for code that needs the truth, and
970
+ ``isinstance(proxy, _DeprecatedProxy)`` remains ``True`` via the ``type()`` fast path.
971
+ No warning is emitted — type checks are structural, matching
972
+ :meth:`~deprecate.proxy._DeprecatedProxy.__instancecheck__`.
973
+
974
+ *Class* proxies (``deprecated_class`` aliases) deliberately keep reporting the proxy
975
+ class: forwarding the metaclass would make ``isinstance(proxy, type)`` true, and
976
+ class-dispatching decorators (e.g. PEP 702 ``typing_extensions.deprecated``) would then
977
+ patch the wrapped class in place instead of wrapping the proxy callable. Class-side
978
+ transparency is provided by ``__instancecheck__``/``__subclasscheck__`` instead.
979
+
980
+ """
981
+ active = _DeprecatedProxy._get_static_attr_owner(self)
982
+ if isinstance(active, type):
983
+ return type(self)
984
+ return type(active)
985
+
986
+ def __instancecheck__(self, instance: object) -> bool:
987
+ """Support ``isinstance(x, proxy)`` by delegating to the active class.
988
+
989
+ Allows a proxy used as a deprecated class alias to work transparently with ``isinstance`` without emitting a
990
+ warning — type checks are structural, not a use of the deprecated API.
991
+
992
+ When the active object is itself a :class:`_DeprecatedProxy` (stacked proxy chain), the loop walks inward until
993
+ a concrete type is reached. Defensive cycle guard breaks the loop on the unlikely case of a circular stack so
994
+ this dunder never blocks.
995
+
996
+ Raises ``TypeError`` (mirroring the builtin) when the active object is an instance rather than a type — using an
997
+ *instance* proxy as the second argument to ``isinstance`` is a misuse. Returns ``False`` only on a circular
998
+ proxy stack.
999
+
1000
+ """
1001
+ seen: set[int] = set()
1002
+ active = self._get_active()
1003
+ while isinstance(active, _DeprecatedProxy):
1004
+ if id(active) in seen:
1005
+ return False
1006
+ seen.add(id(active))
1007
+ active = active._get_active()
1008
+ if isinstance(active, type):
1009
+ # Delegate via isinstance to preserve metaclass-defined instance checks.
1010
+ return isinstance(instance, active)
1011
+ # Active object is an instance, not a class: using an *instance* proxy as the second argument to
1012
+ # ``isinstance`` is a misuse. Raise the same ``TypeError`` the builtin does instead of silently
1013
+ # returning ``False`` (which hid the mistake).
1014
+ raise TypeError("isinstance() arg 2 must be a type, a tuple of types, or a union")
1015
+
1016
+ def __subclasscheck__(self, subclass: type) -> bool:
1017
+ """Support ``issubclass(X, proxy)`` by delegating to the active class.
1018
+
1019
+ Same rationale as :meth:`~deprecate.proxy._DeprecatedProxy.__instancecheck__` — no warning emitted.
1020
+ Stacked proxy chains are walked iteratively until a concrete type is reached; a defensive cycle guard
1021
+ breaks the loop on the unlikely case of a circular stack.
1022
+
1023
+ Raises ``TypeError`` (mirroring the builtin) when the active object is an instance rather than a type.
1024
+ Returns ``False`` only on a circular proxy stack.
1025
+
1026
+ """
1027
+ seen: set[int] = set()
1028
+ active = self._get_active()
1029
+ while isinstance(active, _DeprecatedProxy):
1030
+ if id(active) in seen:
1031
+ return False
1032
+ seen.add(id(active))
1033
+ active = active._get_active()
1034
+ if isinstance(active, type):
1035
+ # Delegate via issubclass so that any metaclass-defined
1036
+ # __subclasscheck__ (e.g., from abc.ABCMeta) is respected.
1037
+ return issubclass(subclass, active)
1038
+ # Active object is an instance, not a class: using an *instance* proxy as the second argument to
1039
+ # ``issubclass`` is a misuse. Raise the same ``TypeError`` the builtin does instead of silently
1040
+ # returning ``False`` (which hid the mistake).
1041
+ raise TypeError("issubclass() arg 2 must be a class, a tuple of classes, or a union")
1042
+
1043
+ # ------------------------------------------------------------------
1044
+ # Subclassing protocol (PEP 560) — supports ``class Child(DeprecatedAlias)``
1045
+ # ------------------------------------------------------------------
1046
+
1047
+ def __mro_entries__(self, bases: tuple[Any, ...]) -> tuple[Any, ...]:
1048
+ """Resolve the proxy to the active class when it appears in a subclass ``bases`` list.
1049
+
1050
+ ``deprecated_class`` replaces the class binding with a (non-``type``) proxy, so ``class Child(OldName)`` would
1051
+ otherwise pass the proxy to the class machinery and fail with an opaque metaclass arity error. PEP 560's
1052
+ ``__mro_entries__`` hook lets the proxy substitute the concrete active class (unwrapping any stacked-proxy
1053
+ chain) so the subclass transparently derives from the replacement.
1054
+
1055
+ Subclassing *is* a use of the deprecated name, so a warning is emitted here — except for
1056
+ :attr:`~deprecate._types.TargetMode.ATTRS_REMAP` / :attr:`~deprecate._types.TargetMode.ARGS_REMAP`, whose
1057
+ deprecation scope is a specific set of attributes/arguments rather than the class itself (consistent with
1058
+ :meth:`__call__` and :meth:`__getattr__`).
1059
+
1060
+ """
1061
+ if self._dep.target not in (TargetMode.ATTRS_REMAP, TargetMode.ARGS_REMAP):
1062
+ self._warn()
1063
+ return (_DeprecatedProxy._get_static_attr_owner(self),)
1064
+
1065
+ # ------------------------------------------------------------------
1066
+ # Context-manager protocol — entry warns (a use), exit is silent cleanup
1067
+ # ------------------------------------------------------------------
1068
+
1069
+ def __enter__(self) -> Any: # noqa: ANN401
1070
+ """Enter the active object's context, emitting a deprecation warning."""
1071
+ self._warn()
1072
+ return self._get_active().__enter__()
1073
+
1074
+ def __exit__(self, *exc_info: Any) -> Any: # noqa: ANN401
1075
+ """Exit the active object's context without emitting a warning (cleanup half of the pair)."""
1076
+ return self._get_active().__exit__(*exc_info)
1077
+
1078
+ async def __aenter__(self) -> Any: # noqa: ANN401
1079
+ """Async-enter the active object's context, emitting a deprecation warning."""
1080
+ self._warn()
1081
+ return await self._get_active().__aenter__()
1082
+
1083
+ async def __aexit__(self, *exc_info: Any) -> Any: # noqa: ANN401
1084
+ """Async-exit the active object's context without emitting a warning (cleanup half of the pair)."""
1085
+ return await self._get_active().__aexit__(*exc_info)
1086
+
1087
+ def __aiter__(self) -> Any: # noqa: ANN401
1088
+ """Return the active object's async iterator, emitting a deprecation warning."""
1089
+ self._warn()
1090
+ return self._get_active().__aiter__()
1091
+
1092
+ def __anext__(self) -> Any: # noqa: ANN401
1093
+ """Return the active object's next awaitable, emitting a deprecation warning."""
1094
+ self._warn()
1095
+ return self._get_active().__anext__()
1096
+
1097
+ def __await__(self) -> Any: # noqa: ANN401
1098
+ """Await the active object, emitting a deprecation warning."""
1099
+ self._warn()
1100
+ return self._get_active().__await__()
1101
+
1102
+ # ------------------------------------------------------------------
1103
+ # Numeric/string dunders with non-uniform signatures — hand-written
1104
+ # ------------------------------------------------------------------
1105
+
1106
+ def __round__(self, ndigits: Any = None) -> Any: # noqa: ANN401
1107
+ """Round the active object, emitting a deprecation warning (numeric read)."""
1108
+ self._warn()
1109
+ active = self._get_active()
1110
+ return round(active) if ndigits is None else round(active, ndigits)
1111
+
1112
+ def __format__(self, format_spec: str) -> str:
1113
+ """Format the active object without emitting a warning (a repr-like probe, mirroring ``__str__``)."""
1114
+ return format(self._get_active(), format_spec)
1115
+
1116
+
1117
+ def _proxy_call_with_positional_split(
1118
+ ctor: Callable[..., Any],
1119
+ dep: DeprecationConfig,
1120
+ args: tuple[Any, ...],
1121
+ mapped_kwargs: dict[str, Any],
1122
+ ) -> Any: # noqa: ANN401
1123
+ """Invoke *ctor*, forwarding kwargs bound to POSITIONAL_ONLY constructor params positionally.
1124
+
1125
+ Adopts the ``@deprecated`` dispatcher's split approach: remapped values whose target parameter is positional-only
1126
+ are reordered into positional arguments by declaration order, after the ``consumed=len(args)`` slots the caller
1127
+ already filled positionally. This keeps required positional-only params, immutable (frozen-dataclass-style)
1128
+ instances, and constructor-derived state working — unlike the historical pop-and-``setattr`` fallback.
1129
+
1130
+ """
1131
+ if dep.target_positional_only:
1132
+ pos_args, kw_args = _split_positional_only_kwargs(
1133
+ dep.target_positional_only_order, mapped_kwargs, dep.target_positional_only, consumed=len(args)
1134
+ )
1135
+ return ctor(*args, *pos_args, **kw_args)
1136
+ return ctor(*args, **mapped_kwargs)
1137
+
1138
+
1139
+ def _reconstruct_proxy(
1140
+ cfg: _ProxyConfig,
1141
+ dep: DeprecationConfig,
1142
+ doc: Optional[str],
1143
+ ) -> "_DeprecatedProxy":
1144
+ """Rebuild a :class:`_DeprecatedProxy` from its config dataclasses without re-running ``__init__``.
1145
+
1146
+ Used by ``__copy__`` and as the pickle reconstructor in ``__reduce_ex__``: re-running
1147
+ ``__init__`` would repeat decoration-time validation and misconfiguration warnings, so the
1148
+ state is re-attached directly via ``object.__setattr__`` (bypassing the proxy's forwarding
1149
+ ``__setattr__``).
1150
+
1151
+ Args:
1152
+ cfg: Private mutable runtime state for the new proxy.
1153
+ dep: Frozen deprecation metadata (shared or copied by the caller as appropriate).
1154
+ doc: Instance-level ``__doc__`` mirrored from the wrapped object, or ``None`` when the
1155
+ original proxy carried no instance docstring.
1156
+
1157
+ """
1158
+ proxy = _DeprecatedProxy.__new__(_DeprecatedProxy)
1159
+ object.__setattr__(proxy, "_DeprecatedProxy__config", cfg)
1160
+ object.__setattr__(proxy, "__deprecated__", dep)
1161
+ if doc is not None:
1162
+ object.__setattr__(proxy, "__doc__", doc)
1163
+ return proxy
1164
+
1165
+
1166
+ def _proxy_call_args_remap(
1167
+ proxy: _DeprecatedProxy,
1168
+ dep: DeprecationConfig,
1169
+ cfg: _ProxyConfig,
1170
+ args: tuple[Any, ...],
1171
+ kwargs: dict[str, Any],
1172
+ ) -> Any: # noqa: ANN401
1173
+ """Handle ``TargetMode.ARGS_REMAP`` branch of ``__call__``: warn per deprecated kwarg, remap, call obj."""
1174
+ mapping = dep.args_mapping or {}
1175
+ for old_key in mapping:
1176
+ if old_key in kwargs:
1177
+ proxy._warn(arg_name=old_key, _extra_frames=1)
1178
+ mapped_kwargs = proxy._apply_args_mapping(kwargs)
1179
+ mapped_kwargs = proxy._merge_args_extra(mapped_kwargs)
1180
+ return _proxy_call_with_positional_split(cfg.obj, dep, args, mapped_kwargs)
1181
+
1182
+
1183
+ def _proxy_call_callable_with_mapping(
1184
+ proxy: _DeprecatedProxy,
1185
+ dep: DeprecationConfig,
1186
+ target_fn: Callable[..., Any],
1187
+ args: tuple[Any, ...],
1188
+ kwargs: dict[str, Any],
1189
+ ) -> Any: # noqa: ANN401
1190
+ """Handle callable-target + args_mapping branch of ``__call__``: warn per kwarg, remap, forward."""
1191
+ mapping = dep.args_mapping or {}
1192
+ for old_key in mapping:
1193
+ if old_key in kwargs:
1194
+ proxy._warn(arg_name=old_key, _extra_frames=1)
1195
+ if not any(old_key in kwargs for old_key in mapping):
1196
+ proxy._warn(_extra_frames=1)
1197
+ mapped_kwargs = proxy._apply_args_mapping(kwargs)
1198
+ mapped_kwargs = proxy._merge_args_extra(mapped_kwargs)
1199
+ return _proxy_call_with_positional_split(target_fn, dep, args, mapped_kwargs)
1200
+
1201
+
1202
+ def _expand_dc_attrs_to_args(
1203
+ dc_check: Any, # noqa: ANN401
1204
+ attrs_mapping: Optional[dict[str, Optional[str]]],
1205
+ args_mapping: Optional[dict[str, Optional[str]]],
1206
+ ) -> tuple[Optional[dict[str, Optional[str]]], list[str]]:
1207
+ """Auto-expand ``attrs_mapping`` entries into ``args_mapping`` for dataclass dual-surface deprecation.
1208
+
1209
+ When the target (or wrapped object) is a ``@dataclass``, copies ``attrs_mapping`` entries whose redirect value names
1210
+ a dataclass ``__init__`` parameter into ``args_mapping`` so that both ``instance.old_field`` (attribute access) and
1211
+ ``DC(old_field=5)`` (constructor kwarg) emit a ``FutureWarning`` from a single ``deprecated_class()`` call.
1212
+
1213
+ Returns ``(updated_args_mapping, auto_expanded_keys)``. Returns the original ``args_mapping`` unchanged (possibly
1214
+ ``None``) when ``attrs_mapping`` is empty/``None`` or ``dc_check`` is not a dataclass. Keys already present in
1215
+ ``args_mapping`` are never overwritten.
1216
+
1217
+ """
1218
+ if not (attrs_mapping and _is_dataclass_target(dc_check)):
1219
+ return args_mapping, []
1220
+ auto_expanded: list[str] = []
1221
+ _init_param_names: set[str] = set(inspect.signature(dc_check).parameters)
1222
+ for _old_key, _mapping_val in attrs_mapping.items():
1223
+ if _mapping_val in _init_param_names:
1224
+ if args_mapping is None:
1225
+ args_mapping = {}
1226
+ if _old_key not in args_mapping:
1227
+ args_mapping[_old_key] = _mapping_val
1228
+ auto_expanded.append(_old_key)
1229
+ return args_mapping, auto_expanded
1230
+
1231
+
1232
+ def _detect_ctor_positional_only(dc_check: Any) -> tuple[frozenset[str], tuple[str, ...]]: # noqa: ANN401
1233
+ """Inspect the active class constructor for POSITIONAL_ONLY parameters.
1234
+
1235
+ Proxy twin of :func:`~deprecate.deprecation._detect_positional_only`: pre-computes the split
1236
+ data consumed by :func:`_proxy_call_with_positional_split` so remapped kwargs bound to
1237
+ positional-only constructor params can be forwarded positionally at call time.
1238
+
1239
+ Args:
1240
+ dc_check: The resolved active object (target class when configured, wrapped object
1241
+ otherwise). Non-class objects yield empty results.
1242
+
1243
+ Returns:
1244
+ Tuple of ``(positional_only, param_order)`` — the POSITIONAL_ONLY parameter names of the
1245
+ constructor and the full parameter-name sequence in declaration order (``self`` excluded,
1246
+ matching ``inspect.signature`` on a class). Both empty when *dc_check* is not a class or
1247
+ its constructor declares no positional-only params.
1248
+
1249
+ """
1250
+ if not isinstance(dc_check, type):
1251
+ return frozenset(), ()
1252
+ try:
1253
+ ctor_sig = inspect.signature(dc_check)
1254
+ except (TypeError, ValueError):
1255
+ return frozenset(), ()
1256
+ positional_only = frozenset(
1257
+ param_name
1258
+ for param_name, param in ctor_sig.parameters.items()
1259
+ if param.kind is inspect.Parameter.POSITIONAL_ONLY
1260
+ )
1261
+ param_order: tuple[str, ...] = tuple(ctor_sig.parameters) if positional_only else ()
1262
+ return positional_only, param_order
1263
+
1264
+
1265
+ def _detect_proxy_positional_only(
1266
+ dc_check: Any, # noqa: ANN401
1267
+ name: str,
1268
+ args_mapping: Optional[dict[str, Optional[str]]],
1269
+ ) -> tuple[str, ...]:
1270
+ """Detect ``args_mapping`` keys that remap to POSITIONAL_ONLY constructor parameters.
1271
+
1272
+ Emits a ``UserWarning`` at decoration time and returns the incompatible old-key names so they can be recorded in
1273
+ :class:`~deprecate._types.DeprecationConfig` for audit surfacing. Returns an empty tuple when no incompatibilities
1274
+ are found.
1275
+
1276
+ """
1277
+ if not (args_mapping and isinstance(dc_check, type)):
1278
+ return ()
1279
+ incompatible = _get_args_mapping_positional_only_keys(dc_check, args_mapping)
1280
+ if incompatible:
1281
+ warnings.warn(
1282
+ f"`args_mapping` on `{name}` remaps {list(incompatible)!r} to POSITIONAL_ONLY "
1283
+ f"constructor parameter(s) of `{dc_check.__name__}`. "
1284
+ "Calls using those deprecated names will pass the remapped values positionally "
1285
+ "to the constructor — consider removing `/` from the target signature or using "
1286
+ "`attrs_mapping` instead.",
1287
+ UserWarning,
1288
+ stacklevel=5, # caller → decorator(cls) → __init__ → _detect_proxy_positional_only → warn
1289
+ )
1290
+ return incompatible
1291
+
1292
+
1293
+ def _build_proxy_warn_msg(
1294
+ proxy: _DeprecatedProxy,
1295
+ arg_name: Optional[str],
1296
+ dep: DeprecationConfig,
1297
+ cfg: _ProxyConfig,
1298
+ ) -> Optional[str]:
1299
+ """Build the warning message string for a proxy warning emission.
1300
+
1301
+ Returns ``None`` when the warning should be suppressed (``attrs_mapping`` lookup miss).
1302
+
1303
+ """
1304
+ target: Any = dep.target
1305
+ args_mapping = dep.args_mapping
1306
+ custom_template = cfg.template_mgs
1307
+
1308
+ if arg_name is not None and args_mapping and arg_name in args_mapping:
1309
+ new_arg = args_mapping[arg_name]
1310
+ argument_map = TEMPLATE_ARGUMENT_MAPPING % {"old_arg": arg_name, "new_arg": str(new_arg)}
1311
+ template = custom_template or TEMPLATE_WARNING_ARGUMENTS
1312
+ return template % {
1313
+ "source_name": dep.name,
1314
+ "source_path": dep.name,
1315
+ "deprecated_in": dep.deprecated_in,
1316
+ "remove_in": dep.remove_in,
1317
+ "target_name": str(new_arg) if new_arg is not None else "",
1318
+ "target_path": "",
1319
+ "argument_map": argument_map,
1320
+ }
1321
+ if arg_name is not None and arg_name.startswith("__attr__:") and dep.attrs_mapping is not None:
1322
+ return proxy._build_attr_warning_msg(arg_name, dep, dep.attrs_mapping, target, custom_template)
1323
+ if callable(target):
1324
+ target_name = target.__name__
1325
+ target_path = f"{target.__module__}.{target_name}"
1326
+ template = custom_template or TEMPLATE_WARNING_CALLABLE
1327
+ return template % {
1328
+ "source_name": dep.name,
1329
+ "source_path": dep.name,
1330
+ "deprecated_in": dep.deprecated_in,
1331
+ "remove_in": dep.remove_in,
1332
+ "target_name": target_name,
1333
+ "target_path": target_path,
1334
+ "argument_map": "",
1335
+ }
1336
+ template = custom_template or TEMPLATE_WARNING_NO_TARGET
1337
+ return template % {
1338
+ "source_name": dep.name,
1339
+ "source_path": dep.name,
1340
+ "deprecated_in": dep.deprecated_in,
1341
+ "remove_in": dep.remove_in,
1342
+ "target_name": "",
1343
+ "target_path": "",
1344
+ "argument_map": "",
1345
+ }
1346
+
1347
+
1348
+ def deprecated_class(
1349
+ target: Any = None, # noqa: ANN401
1350
+ *,
1351
+ deprecated_in: str = "",
1352
+ remove_in: str = "",
1353
+ num_warns: int = 1,
1354
+ stream: Optional[Callable[..., None]] = deprecation_warning,
1355
+ template_mgs: Optional[str] = None,
1356
+ args_mapping: Optional[dict[str, Optional[str]]] = None,
1357
+ args_extra: Optional[dict[str, Any]] = None,
1358
+ attrs_mapping: Optional[dict[str, Optional[str]]] = None,
1359
+ update_docstring: bool = False,
1360
+ docstring_style: Literal["auto", "rst", "mkdocs", "markdown"] = "auto",
1361
+ _misconfigured_override: bool = False,
1362
+ ) -> Callable[[Union[type, "_DeprecatedProxy"]], "_DeprecatedProxy"]:
1363
+ r"""Decorator factory for deprecating class definitions with optional target redirection.
1364
+
1365
+ Apply ``@deprecated_class(...)`` to an Enum or dataclass to wrap the class in a
1366
+ :class:`~deprecate.proxy._DeprecatedProxy`. All attribute, item, and call access on the resulting object will
1367
+ emit a deprecation warning and, if *target* is provided, will be forwarded to the replacement class.
1368
+
1369
+ Args:
1370
+ target: Optional replacement class to redirect all access to.
1371
+ deprecated_in: Version string when the class was deprecated.
1372
+ remove_in: Version string when the class will be removed.
1373
+ num_warns: Maximum number of warnings to emit per proxy instance. ``1`` warns once; ``-1`` warns on every
1374
+ access.
1375
+ stream: Callable used to emit warnings. Defaults to :data:`~deprecate.deprecation.deprecation_warning`.
1376
+ template_mgs: Optional custom warning message template that overrides the built-in templates. When ``None``
1377
+ (default), the built-in template for the active scenario is used (callable-target, no-target, or
1378
+ per-argument for ``args_mapping``). Available ``%``-style placeholders:
1379
+
1380
+ - ``%(source_name)s`` — the deprecated class name (taken from ``cls.__name__``)
1381
+ - ``%(deprecated_in)s`` — value of the ``deprecated_in`` argument
1382
+ - ``%(remove_in)s`` — value of the ``remove_in`` argument
1383
+ - ``%(target_name)s`` — target class name (only when *target* is callable)
1384
+ - ``%(target_path)s`` — fully-qualified target path (only when *target* is callable)
1385
+ - ``%(argument_map)s`` — formatted ``\`old\` -> \`new\``` string (only for per-argument warnings
1386
+ emitted by ``args_mapping``)
1387
+
1388
+ Example: ``"v%(deprecated_in)s: ``%(source_name)s`` -> ``%(target_name)s``"``.
1389
+ args_mapping: Optional dict remapping keyword argument names when the decorated class is called. Keys are
1390
+ old argument names; values are new names, or ``None`` to drop the argument entirely. When provided
1391
+ without an explicit callable *target*, the mode auto-resolves to
1392
+ :attr:`~deprecate._types.TargetMode.ARGS_REMAP`: the proxy warns **only when an old argument name is
1393
+ actually used** in the call, matching the per-argument warning behaviour of
1394
+ ``@deprecated(target=TargetMode.ARGS_REMAP, args_mapping=...)``. Passing ``args_mapping`` together with
1395
+ ``target=TargetMode.NOTIFY`` is a misconfiguration and emits a :class:`UserWarning` at decoration time
1396
+ (will be :class:`TypeError` in v1.0). Similarly, ``target=TargetMode.ARGS_REMAP`` without
1397
+ ``args_mapping`` emits a :class:`UserWarning` at decoration time.
1398
+ args_extra: Optional dict of extra keyword arguments merged into the forwarded call after ``args_mapping`` has
1399
+ been applied. ``args_extra`` values win over any caller-supplied value with the same key (i.e.
1400
+ ``args_extra`` > explicit new-name kwarg > remapped old-name value > source defaults). Ignored when
1401
+ ``target`` is :attr:`~deprecate._types.TargetMode.NOTIFY` (passing both emits a :class:`UserWarning` at
1402
+ decoration time; will be :class:`TypeError` in v1.0).
1403
+ attrs_mapping: Optional dict mapping deprecated attribute names to canonical names (or ``None`` for
1404
+ warn-only). When set, only the listed attribute names emit a deprecation warning on access; all other
1405
+ attributes are forwarded silently. The redirect applies to reads (``__getattr__``), writes
1406
+ (``__setattr__``), and deletes (``__delattr__``). Every non-``None`` value must be an existing attribute
1407
+ on the target class when ``target`` is provided, or on the wrapped source class otherwise.
1408
+ ``None`` values keep the same attribute name but still resolve against the active class, so with
1409
+ ``target=SomeClass`` a warn-only mapping such as ``{"size": None}`` reads, writes, and deletes
1410
+ ``SomeClass.size``.
1411
+ Redirect chains such as ``{"a": "b", "b": "c"}`` are allowed at decoration time and reported by audit as
1412
+ :attr:`~deprecate.audit.ChainType.STACKED`. Cycles such as ``{"a": "b", "b": "a"}`` raise
1413
+ :class:`ValueError` at decoration time.
1414
+
1415
+ Example: ``attrs_mapping={"color": "colour", "txt": "text"}`` warns on ``proxy.color`` access and
1416
+ returns ``proxy.colour``; ``proxy.colour`` is forwarded silently.
1417
+
1418
+ When ``attrs_mapping`` is ``None`` (default), the existing behaviour is preserved: a warning is emitted
1419
+ on every attribute access through the proxy.
1420
+
1421
+ **Callable target interaction**: when ``target=SomeClass`` is also provided, listed attribute aliases
1422
+ resolve against ``SomeClass``. A ``None`` mapping keeps the original attribute name on ``SomeClass``.
1423
+ Unlisted attributes and calls continue to use the normal target-forwarding behaviour.
1424
+
1425
+ **Validation limitation**: attribute existence is checked using :func:`inspect.getattr_static`,
1426
+ which detects class-level attributes and ``__slots__`` entries but not instance-only attributes
1427
+ set in ``__init__`` via ``self.x = ...``. For dataclass targets without defaults, the field
1428
+ name appears in ``__dataclass_fields__`` but the attribute itself is instance-only —
1429
+ decoration-time validation will raise :class:`ValueError` even though access would succeed at
1430
+ runtime. As a workaround, add a class-level default or use a ``None`` (warn-only) entry.
1431
+
1432
+ The mode can also be set explicitly as ``target=TargetMode.ATTRS_REMAP`` — both forms are equivalent;
1433
+ the explicit form is self-documenting and enables validation at decoration time. Passing
1434
+ ``target=TargetMode.ATTRS_REMAP`` without ``attrs_mapping``, or passing an empty ``attrs_mapping={}``,
1435
+ emits a :class:`UserWarning` at decoration time (will be :class:`TypeError` in v1.0). Passing
1436
+ ``attrs_mapping`` together with ``target=TargetMode.NOTIFY`` is also a misconfiguration and emits a
1437
+ :class:`UserWarning` at decoration time.
1438
+ update_docstring: If ``True``, inject a deprecation notice into the class docstring at decoration time (same
1439
+ behaviour as ``@deprecated(update_docstring=True)``).
1440
+ docstring_style: Output style for the injected notice when ``update_docstring=True``. ``"auto"`` detects the
1441
+ doc engine at decoration time; ``"rst"`` emits a ``.. deprecated::`` directive; ``"mkdocs"`` /
1442
+ ``"markdown"`` emit a ``!!! warning`` admonition.
1443
+
1444
+ Returns:
1445
+ A decorator that wraps the class in a :class:`~deprecate.proxy._DeprecatedProxy`.
1446
+
1447
+ Note:
1448
+ **Subclassing (PEP 560)**: the proxy implements ``__mro_entries__`` so
1449
+ ``class Child(deprecated_alias):`` resolves to ``class Child(target_or_source_class):``
1450
+ in the MRO — ``issubclass(Child, target_class)`` returns ``True`` and standard inheritance
1451
+ semantics are preserved. One ``FutureWarning`` fires at class-definition time (not per
1452
+ instance). With :attr:`~deprecate._types.TargetMode.ATTRS_REMAP` aliases (``attrs_mapping``
1453
+ without a callable *target*) and :attr:`~deprecate._types.TargetMode.ARGS_REMAP` aliases
1454
+ (``args_mapping`` without a callable *target*) subclassing stays **silent** — both modes
1455
+ scope deprecation to specific axes (attribute names or argument names), not the class name.
1456
+
1457
+ Examples:
1458
+ >>> from enum import Enum
1459
+ >>> class NewColor(Enum):
1460
+ ... RED = 1
1461
+ >>> @deprecated_class(target=NewColor, deprecated_in="1.0", remove_in="2.0", stream=None)
1462
+ ... class OldColor(Enum):
1463
+ ... RED = 1
1464
+ >>> OldColor.RED is NewColor.RED
1465
+ True
1466
+ >>> OldColor(1) is NewColor.RED
1467
+ True
1468
+
1469
+ When only argument names changed, omit *target* and supply ``args_mapping``. The proxy auto-resolves to
1470
+ :attr:`~deprecate._types.TargetMode.ARGS_REMAP` and warns **only when the old argument name is passed**:
1471
+
1472
+ >>> class Config:
1473
+ ... def __init__(self, timeout: int = 0) -> None:
1474
+ ... self.timeout = timeout
1475
+ >>> LegacyConfig = deprecated_class(
1476
+ ... args_mapping={"time_limit": "timeout"},
1477
+ ... deprecated_in="1.5", remove_in="2.0", stream=None,
1478
+ ... )(Config)
1479
+ >>> LegacyConfig(timeout=30).timeout # new name — no remap needed
1480
+ 30
1481
+ >>> LegacyConfig(time_limit=30).timeout # old name — remapped to timeout
1482
+ 30
1483
+
1484
+ Selective per-attribute deprecation via ``attrs_mapping``: only the listed attribute
1485
+ aliases emit a warning; other attribute accesses pass through silently.
1486
+
1487
+ >>> @deprecated_class(
1488
+ ... attrs_mapping={"color": "colour"},
1489
+ ... deprecated_in="1.0",
1490
+ ... remove_in="2.0",
1491
+ ... stream=None,
1492
+ ... )
1493
+ ... class Palette:
1494
+ ... colour = "red"
1495
+ ... color = colour # deprecated alias for ``colour``
1496
+ >>> Palette.colour # canonical name — silent passthrough
1497
+ 'red'
1498
+ >>> Palette.color # deprecated alias — warns (suppressed by ``stream=None``)
1499
+ 'red'
1500
+
1501
+ """
1502
+
1503
+ def decorator(cls: Union[type, "_DeprecatedProxy"]) -> "_DeprecatedProxy":
1504
+ # When cls is a _DeprecatedProxy (stacking case), cls.__name__ triggers __getattr__
1505
+ # which emits a spurious warning. Retrieve the name safely via the stored metadata.
1506
+ cls_name = (
1507
+ object.__getattribute__(cls, "__deprecated__").name if isinstance(cls, _DeprecatedProxy) else cls.__name__
1508
+ )
1509
+ if stream is not None and not deprecated_in and not template_mgs:
1510
+ warnings.warn(
1511
+ f"`@deprecated_class` on `{cls_name}` has no `deprecated_in` set."
1512
+ " Deprecation notices and generated documentation will omit the `deprecated_in` version."
1513
+ " Pass `deprecated_in` for a meaningful deprecation notice.",
1514
+ UserWarning,
1515
+ stacklevel=2,
1516
+ )
1517
+ proxy = _DeprecatedProxy(
1518
+ obj=cls,
1519
+ name=cls_name,
1520
+ deprecated_in=deprecated_in,
1521
+ remove_in=remove_in,
1522
+ num_warns=num_warns,
1523
+ stream=stream,
1524
+ template_mgs=template_mgs,
1525
+ read_only=False,
1526
+ target=target,
1527
+ args_mapping=args_mapping,
1528
+ args_extra=args_extra,
1529
+ attrs_mapping=attrs_mapping,
1530
+ docstring_style=docstring_style,
1531
+ _misconfigured_override=_misconfigured_override,
1532
+ )
1533
+ if update_docstring:
1534
+ # Use a SimpleNamespace shim so _update_docstring_with_deprecation can set __doc__ normally; then store
1535
+ # the result on the proxy via object.__setattr__ (bypassing the proxy's forwarding __setattr__).
1536
+ shim = types.SimpleNamespace(__doc__=object.__getattribute__(proxy, "__doc__"), __deprecated__=proxy._dep)
1537
+ _update_docstring_with_deprecation(shim)
1538
+ object.__setattr__(proxy, "__doc__", shim.__doc__)
1539
+ return proxy
1540
+
1541
+ return decorator
1542
+
1543
+
1544
+ def deprecated_instance(
1545
+ obj: Any, # noqa: ANN401
1546
+ *,
1547
+ name: str = "",
1548
+ deprecated_in: str = "",
1549
+ remove_in: str = "",
1550
+ num_warns: int = 1,
1551
+ stream: Optional[Callable[..., None]] = deprecation_warning,
1552
+ template_mgs: Optional[str] = None,
1553
+ read_only: bool = False,
1554
+ args_extra: Optional[dict[str, Any]] = None,
1555
+ ) -> "_DeprecatedProxy":
1556
+ """Wrap any Python object with deprecation warnings.
1557
+
1558
+ Returns a :class:`~deprecate.proxy._DeprecatedProxy` that transparently forwards all read access to *obj* while
1559
+ emitting a :class:`FutureWarning`. In *read-only* mode any write attempt through the proxy raises
1560
+ :class:`AttributeError`.
1561
+
1562
+ Args:
1563
+ obj: The object to deprecate (dict, list, custom object, …).
1564
+ name: Display name for *obj* used in the warning message. When omitted, the type name of *obj* is used
1565
+ (e.g. ``"dict"``).
1566
+ deprecated_in: Version string when *obj* was deprecated.
1567
+ remove_in: Version string when *obj* will be removed.
1568
+ num_warns: Maximum number of warnings to emit. ``1`` (default) warns once; ``-1`` warns on every access.
1569
+ stream: Callable used to emit warnings. Defaults to :data:`~deprecate.deprecation.deprecation_warning`
1570
+ (:class:`FutureWarning`). Pass ``None`` to suppress warnings.
1571
+ template_mgs: Optional custom warning message template that overrides the built-in templates. When ``None``
1572
+ (default), the built-in template for the active scenario is used. See
1573
+ :func:`~deprecate.proxy.deprecated_class` for the available ``%``-style placeholders.
1574
+ read_only: If ``True``, raise :class:`AttributeError` on any write attempt through the proxy.
1575
+ Only the following standard collection mutator names are intercepted: ``append``, ``clear``,
1576
+ ``discard``, ``extend``, ``insert``, ``pop``, ``remove``, ``setdefault``, ``update``, ``add``.
1577
+ Custom method names (e.g. ``register()``, ``reload()``, ``set_value()``) are not blocked.
1578
+ args_extra: Optional dict of extra keyword arguments merged into the forwarded call when the proxy is invoked.
1579
+ ``args_extra`` values win over any caller-supplied value with the same key.
1580
+
1581
+ Returns:
1582
+ A :class:`~deprecate.proxy._DeprecatedProxy` wrapping *obj*.
1583
+
1584
+ Note:
1585
+ **Operator warnings**: arithmetic operators (``+``, ``-``, ``*``, ``**``, ``//``, ``%``, ``<<``,
1586
+ ``>>``, ``&``, ``|``, ``^``) and their reflected forms emit a deprecation warning and consume the
1587
+ ``num_warns`` budget. In-place operators (``+=``, ``-=``, …) additionally enforce ``read_only``.
1588
+ Ordering comparisons (``<``, ``<=``, ``>``, ``>=``) and structural probes (``__eq__``, ``__len__``,
1589
+ ``__bool__``, ``__str__``) are **silent** — they do not consume the warn budget.
1590
+
1591
+ Example:
1592
+ >>> cfg = {"threshold": 0.5, "enabled": True}
1593
+ >>> proxy = deprecated_instance(
1594
+ ... cfg,
1595
+ ... name="config_dict",
1596
+ ... deprecated_in="1.0",
1597
+ ... remove_in="2.0",
1598
+ ... stream=None,
1599
+ ... )
1600
+ >>> proxy["threshold"]
1601
+ 0.5
1602
+ >>> proxy.get("enabled")
1603
+ True
1604
+
1605
+ """
1606
+ resolved_name = name or type(obj).__name__
1607
+ if stream is not None and not deprecated_in and not template_mgs:
1608
+ warnings.warn(
1609
+ f"`deprecated_instance()` on `{resolved_name}` has no `deprecated_in` set."
1610
+ " Deprecation notices and generated documentation will omit the `deprecated_in` version."
1611
+ " Pass `deprecated_in` for a meaningful deprecation notice.",
1612
+ UserWarning,
1613
+ stacklevel=2,
1614
+ )
1615
+ return _DeprecatedProxy(
1616
+ obj=obj,
1617
+ name=resolved_name,
1618
+ deprecated_in=deprecated_in,
1619
+ remove_in=remove_in,
1620
+ num_warns=num_warns,
1621
+ stream=stream,
1622
+ template_mgs=template_mgs,
1623
+ read_only=read_only,
1624
+ args_extra=args_extra,
1625
+ )
1626
+
1627
+
1628
+ # ----------------------------------------------------------------------
1629
+ # Operator / protocol dunder forwarding (see the "Protocol forwarding" section of the
1630
+ # _DeprecatedProxy docstring for the warn-policy contract).
1631
+ #
1632
+ # Implicit special-method lookup bypasses ``__getattr__`` — Python resolves dunders on the *type*,
1633
+ # not the instance — so every operator, conversion, and protocol dunder must live on the class
1634
+ # itself for the proxy to stay transparent. These are generated from a table (rather than ~60
1635
+ # hand-written defs) and installed onto ``_DeprecatedProxy`` below.
1636
+ # ----------------------------------------------------------------------
1637
+
1638
+
1639
+ def _unwrap_operand(value: Any) -> Any: # noqa: ANN401
1640
+ """Return the active object behind a proxy operand, leaving non-proxy operands untouched."""
1641
+ if isinstance(value, _DeprecatedProxy):
1642
+ return _DeprecatedProxy._get_static_attr_owner(value)
1643
+ return value
1644
+
1645
+
1646
+ def _make_binary_forward(op_name: str, *, warn: bool) -> Callable[..., Any]:
1647
+ """Build a binary-operator dunder that forwards to the active object.
1648
+
1649
+ Looks the operator up on the *type* of the active object and returns :data:`NotImplemented` when it is absent, so
1650
+ Python can try the reflected operand and ultimately raise its normal :class:`TypeError` — the proxy never masks an
1651
+ unsupported-operand error. Proxy operands are unwrapped to their active object first.
1652
+
1653
+ """
1654
+
1655
+ def _binary_dunder(self: "_DeprecatedProxy", other: Any, *extra: Any) -> Any: # noqa: ANN401
1656
+ active = self._get_active()
1657
+ impl = getattr(type(active), op_name, None)
1658
+ if impl is None:
1659
+ return NotImplemented
1660
+ result = impl(active, _unwrap_operand(other), *(_unwrap_operand(e) for e in extra))
1661
+ if result is NotImplemented:
1662
+ return NotImplemented
1663
+ if warn:
1664
+ self._warn()
1665
+ return result
1666
+
1667
+ _binary_dunder.__name__ = op_name
1668
+ _binary_dunder.__qualname__ = f"_DeprecatedProxy.{op_name}"
1669
+ return _binary_dunder
1670
+
1671
+
1672
+ def _make_inplace_forward(op_name: str) -> Callable[..., Any]:
1673
+ """Build an in-place operator dunder that enforces ``read_only`` before forwarding.
1674
+
1675
+ In-place operators mutate the active object, so they must honour the ``read_only=True`` contract. This is a
1676
+ separate factory from :func:`_make_binary_forward` so that the check is not paid by the much more common
1677
+ arithmetic/reflected paths.
1678
+
1679
+ """
1680
+
1681
+ def _inplace_dunder(self: "_DeprecatedProxy", other: Any) -> Any: # noqa: ANN401
1682
+ self._check_read_only(f"In-place operation '{op_name}'")
1683
+ active = self._get_active()
1684
+ impl = getattr(type(active), op_name, None)
1685
+ if impl is None:
1686
+ return NotImplemented
1687
+ self._warn()
1688
+ return impl(active, _unwrap_operand(other))
1689
+
1690
+ _inplace_dunder.__name__ = op_name
1691
+ _inplace_dunder.__qualname__ = f"_DeprecatedProxy.{op_name}"
1692
+ return _inplace_dunder
1693
+
1694
+
1695
+ def _make_unary_forward(op_name: str, func: Callable[[Any], Any]) -> Callable[..., Any]:
1696
+ """Build a unary/conversion dunder that forwards through *func* (a builtin such as ``int`` or ``abs``).
1697
+
1698
+ Delegating through the builtin preserves Python's own fallbacks (e.g. ``int()`` falling back to ``__index__``) and
1699
+ lets the natural :class:`TypeError` surface when the active object does not support the protocol.
1700
+
1701
+ """
1702
+
1703
+ def _unary_dunder(self: "_DeprecatedProxy") -> Any: # noqa: ANN401
1704
+ self._warn()
1705
+ return func(self._get_active())
1706
+
1707
+ _unary_dunder.__name__ = op_name
1708
+ _unary_dunder.__qualname__ = f"_DeprecatedProxy.{op_name}"
1709
+ return _unary_dunder
1710
+
1711
+
1712
+ #: Arithmetic, reflected, and in-place binary operators — all warn (a data-producing use).
1713
+ _ARITHMETIC_OPS: tuple[str, ...] = (
1714
+ "__add__", "__sub__", "__mul__", "__matmul__", "__truediv__", "__floordiv__",
1715
+ "__mod__", "__divmod__", "__pow__", "__lshift__", "__rshift__", "__and__", "__xor__", "__or__",
1716
+ ) # fmt: skip
1717
+ _REFLECTED_OPS: tuple[str, ...] = (
1718
+ "__radd__", "__rsub__", "__rmul__", "__rmatmul__", "__rtruediv__", "__rfloordiv__",
1719
+ "__rmod__", "__rdivmod__", "__rpow__", "__rlshift__", "__rrshift__", "__rand__", "__rxor__", "__ror__",
1720
+ ) # fmt: skip
1721
+ _INPLACE_OPS: tuple[str, ...] = (
1722
+ "__iadd__", "__isub__", "__imul__", "__imatmul__", "__itruediv__", "__ifloordiv__",
1723
+ "__imod__", "__ipow__", "__ilshift__", "__irshift__", "__iand__", "__ixor__", "__ior__",
1724
+ ) # fmt: skip
1725
+ #: Ordering comparisons — silent (cheap probes, mirroring ``__eq__``/``__len__``).
1726
+ _ORDERING_OPS: tuple[str, ...] = ("__lt__", "__le__", "__gt__", "__ge__")
1727
+ #: Unary and conversion protocols forwarded through their builtin — all warn (a data-producing use).
1728
+ _UNARY_OPS: dict[str, Callable[[Any], Any]] = {
1729
+ "__neg__": operator.neg,
1730
+ "__pos__": operator.pos,
1731
+ "__abs__": abs,
1732
+ "__invert__": operator.invert,
1733
+ "__int__": int,
1734
+ "__float__": float,
1735
+ "__complex__": complex,
1736
+ "__index__": operator.index,
1737
+ "__trunc__": math.trunc,
1738
+ "__floor__": math.floor,
1739
+ "__ceil__": math.ceil,
1740
+ "__reversed__": reversed,
1741
+ "__fspath__": os.fspath,
1742
+ "__next__": next,
1743
+ }
1744
+
1745
+
1746
+ def _install_forwarding_dunders(cls: type) -> None:
1747
+ """Attach the generated operator/conversion dunders to *cls* at import time.
1748
+
1749
+ Arithmetic and reflected binary operators are installed via :func:`_make_binary_forward`; in-place operators via
1750
+ :func:`_make_inplace_forward` (which also enforces ``read_only``); ordering comparisons via
1751
+ :func:`_make_binary_forward` (silent); unary and conversion protocols via :func:`_make_unary_forward`. Ordering
1752
+ comparisons are silent (structural probes); every other generated dunder warns (data use).
1753
+
1754
+ """
1755
+ for _op in (*_ARITHMETIC_OPS, *_REFLECTED_OPS):
1756
+ setattr(cls, _op, _make_binary_forward(_op, warn=True))
1757
+ for _op in _INPLACE_OPS:
1758
+ setattr(cls, _op, _make_inplace_forward(_op))
1759
+ for _op in _ORDERING_OPS:
1760
+ setattr(cls, _op, _make_binary_forward(_op, warn=False))
1761
+ for _op, _func in _UNARY_OPS.items():
1762
+ setattr(cls, _op, _make_unary_forward(_op, _func))
1763
+
1764
+
1765
+ _install_forwarding_dunders(_DeprecatedProxy)
.venv/lib/python3.12/site-packages/deprecate/utils.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Low-level helpers for the deprecation system.
2
+
3
+ This module provides two kinds of helpers:
4
+
5
+ **Internal** (used by :mod:`deprecate.deprecation` and :mod:`deprecate.audit`):
6
+ - :func:`~deprecate.utils.get_func_arguments_types_defaults`: Extract parameter names, annotations, and defaults
7
+ from a callable's signature. Used when applying ``args_mapping`` and when auditing wrapper configuration.
8
+
9
+ **Public — decorator companion** (exported via :mod:`deprecate`):
10
+ - :func:`~deprecate.utils.void`: Accepts any arguments and returns ``None``. Used in deprecated function stubs
11
+ to satisfy IDEs and mypy about unused parameters.
12
+
13
+ **Public — testing** (exported via :mod:`deprecate`):
14
+ - :func:`~deprecate.utils.assert_no_warnings`: Context manager that asserts no warnings are raised during a
15
+ block — the inverse of ``pytest.warns()``.
16
+
17
+ Copyright (C) 2020-2026 Jiri Borovec <6035284+Borda@users.noreply.github.com>
18
+
19
+ """
20
+
21
+ import inspect
22
+ import warnings
23
+ from collections.abc import Generator
24
+ from contextlib import contextmanager
25
+ from functools import lru_cache
26
+ from types import TracebackType
27
+ from typing import Any, Callable, Optional, Union
28
+
29
+
30
+ def get_func_arguments_types_defaults(func: Callable) -> list[tuple[str, Any, Any]]:
31
+ """Parse function arguments, types and default values.
32
+
33
+ This introspection helper extracts the complete signature information from a function, including parameter names,
34
+ type annotations, and default values. Useful for dynamic argument handling and validation in wrapper functions.
35
+
36
+ Args:
37
+ func: A function to be examined.
38
+
39
+ Returns:
40
+ List of tuples, one per argument, each containing:
41
+ - str: argument name
42
+ - Any: argument type annotation (or inspect.Parameter.empty if no annotation)
43
+ - Any: default value (or inspect.Parameter.empty if no default)
44
+
45
+ Example:
46
+ >>> def example_func(x: int, y: str = "hello", z=42) -> None:
47
+ ... pass
48
+ >>> result = get_func_arguments_types_defaults(example_func)
49
+ >>> for name, type_hint, default in result:
50
+ ... print(f"{name}: type={type_hint}, default={default}")
51
+ x: type=<class 'int'>, default=<class 'inspect._empty'>
52
+ y: type=<class 'str'>, default=hello
53
+ z: type=<class 'inspect._empty'>, default=42
54
+
55
+ Note:
56
+ - Parameters without type annotations have annotation = inspect.Parameter.empty
57
+ - Parameters without defaults have default = inspect.Parameter.empty
58
+ - Excludes *args and **kwargs (use inspect.getfullargspec for those)
59
+
60
+ """
61
+ func_default_params = _get_signature(func).parameters
62
+ func_arg_type_val = []
63
+ for arg in func_default_params:
64
+ param = func_default_params[arg]
65
+ # Exclude ``*args`` / ``**kwargs`` (as the docstring promises): their names are not concrete
66
+ # parameters, and leaking them into caller-argument validation yields a raw ``TypeError`` instead
67
+ # of the curated "argument not accepted by target" message.
68
+ if param.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD):
69
+ continue
70
+ func_arg_type_val.append((arg, param.annotation, param.default))
71
+ return func_arg_type_val
72
+
73
+
74
+ @lru_cache(maxsize=256)
75
+ def _get_signature_cached(func: Callable) -> inspect.Signature:
76
+ """Cache inspect.signature lookups for repeated calls.
77
+
78
+ Uses an LRU cache (maxsize=256) since function signatures are stable at runtime. The size balances reuse for common
79
+ callables without unbounded memory growth.
80
+
81
+ """
82
+ return inspect.signature(func)
83
+
84
+
85
+ def _get_signature(func: Callable) -> inspect.Signature:
86
+ """Get function signature with caching when possible.
87
+
88
+ Falls back to uncached lookup for unhashable callables.
89
+
90
+ """
91
+ try:
92
+ return _get_signature_cached(func)
93
+ except TypeError:
94
+ return inspect.signature(func)
95
+
96
+
97
+ def _is_dataclass_target(cls: Any) -> bool: # noqa: ANN401
98
+ """Return True if *cls* is a dataclass class (not an instance).
99
+
100
+ Used by :class:`~deprecate.proxy._DeprecatedProxy` to detect ``@dataclass`` targets that benefit from automatic
101
+ ``attrs_mapping`` → ``args_mapping`` expansion.
102
+
103
+ """
104
+ import dataclasses
105
+
106
+ return isinstance(cls, type) and dataclasses.is_dataclass(cls)
107
+
108
+
109
+ def _apply_args_mapping_collisions(
110
+ args_mapping: dict[str, Optional[str]],
111
+ kwargs: dict[str, Any],
112
+ args_skip: Any, # noqa: ANN401 - accepts list or set
113
+ name: str,
114
+ stream: Any, # noqa: ANN401 - truthy check; callable in deprecation path
115
+ stacklevel: int,
116
+ ) -> dict[str, Any]:
117
+ """Return snapshot of explicit new-name values for collision pairs and emit UserWarning per collision.
118
+
119
+ A collision occurs when a caller supplies both the deprecated old argument name and its mapped new name
120
+ simultaneously. The new-name value always wins; this function snapshots it before the remap overwrites
121
+ it and warns the caller that the old name was ignored.
122
+
123
+ Args:
124
+ args_mapping: Mapping of old argument names to new names (``None`` = drop).
125
+ kwargs: Current keyword arguments at the call site.
126
+ args_skip: Names whose mapped value is ``None`` (drop); excluded from collision detection.
127
+ name: Callable name used in the warning message.
128
+ stream: Warning stream; falsy value suppresses all warnings.
129
+ stacklevel: Passed to ``warnings.warn``; caller is responsible for counting frames above this function.
130
+
131
+ Returns:
132
+ Dict of ``{new_k: kwargs[new_k]}`` for each detected collision pair (empty when no collisions).
133
+
134
+ """
135
+ collision_pairs = [
136
+ (old_k, new_k)
137
+ for old_k, new_k in args_mapping.items()
138
+ if new_k is not None and old_k in kwargs and new_k in kwargs and new_k not in args_skip
139
+ ]
140
+ explicit_new: dict[str, Any] = {new_k: kwargs[new_k] for _, new_k in collision_pairs}
141
+ if collision_pairs and stream:
142
+ for old_k, new_k in collision_pairs:
143
+ warnings.warn(
144
+ f"Both `{old_k}` (deprecated) and `{new_k}` were supplied to `{name}()`; `{old_k}` is ignored.",
145
+ UserWarning,
146
+ stacklevel=stacklevel,
147
+ )
148
+ return explicit_new
149
+
150
+
151
+ def _get_args_mapping_positional_only_keys(
152
+ target_cls: Any, # noqa: ANN401
153
+ args_mapping: dict[str, Any],
154
+ ) -> tuple[str, ...]:
155
+ """Return ``args_mapping`` keys whose redirect target is a POSITIONAL_ONLY constructor param.
156
+
157
+ When ``deprecated_class(args_mapping={"old": "new"}, ...)`` is applied to a target class whose
158
+ constructor declares ``new`` as positional-only (``def __init__(self, new, /): ...``), calling
159
+ the proxy with ``old=value`` would remap to ``new=value`` and then immediately raise
160
+ ``TypeError`` because ``new`` cannot be passed as a keyword argument.
161
+
162
+ This helper detects that mismatch at decoration time so the proxy can emit a ``UserWarning``
163
+ and store the incompatible keys on :class:`~deprecate._types.DeprecationConfig` for audit
164
+ surfacing.
165
+
166
+ Args:
167
+ target_cls: The resolved target class to inspect.
168
+ args_mapping: The ``args_mapping`` dict being validated.
169
+
170
+ Returns:
171
+ Tuple of ``args_mapping`` old-key names whose remapped target name is positional-only in
172
+ the target's constructor signature. Empty tuple when no incompatibilities detected.
173
+
174
+ """
175
+ try:
176
+ sig = inspect.signature(target_cls)
177
+ except (TypeError, ValueError):
178
+ return ()
179
+
180
+ positional_only: set[str] = {
181
+ name for name, p in sig.parameters.items() if p.kind is inspect.Parameter.POSITIONAL_ONLY
182
+ }
183
+ if not positional_only:
184
+ return ()
185
+
186
+ return tuple(old_key for old_key, mapping_val in args_mapping.items() if mapping_val in positional_only)
187
+
188
+
189
+ def _warns_repr(warns: list[warnings.WarningMessage]) -> list[Union[Warning, str]]:
190
+ """Convert list of warning messages to their string representations.
191
+
192
+ Args:
193
+ warns: List of warning message objects captured during execution.
194
+
195
+ Returns:
196
+ List of warning messages as strings or Warning objects.
197
+
198
+ """
199
+ return [w.message for w in warns]
200
+
201
+
202
+ @contextmanager
203
+ def assert_no_warnings(warning_type: Optional[type[Warning]] = None, match: Optional[str] = None) -> Generator:
204
+ """Context manager asserting that no warnings are raised — the inverse of ``pytest.warns()``.
205
+
206
+ Useful for testing that refactored code properly avoids deprecated functionality or that new implementations don't
207
+ trigger warnings.
208
+
209
+ Args:
210
+ warning_type: The warning type that must NOT be raised (e.g., :class:`FutureWarning`,
211
+ :class:`DeprecationWarning`). If ``None``, asserts that no warnings of any type are raised.
212
+ match: If given, only fail if a warning message contains this string. If ``None``, fails on any warning of
213
+ the specified type.
214
+
215
+ Raises:
216
+ AssertionError: If a warning of the specified type (and optionally matching the message pattern) was raised
217
+ during the context.
218
+
219
+ Example:
220
+ >>> # Assert new function doesn't trigger FutureWarning
221
+ >>> import warnings
222
+ >>> def new_func(x: int) -> int:
223
+ ... return x * 2
224
+ >>> with assert_no_warnings(FutureWarning):
225
+ ... result = new_func(42)
226
+ >>> result
227
+ 84
228
+
229
+ >>> # Assert NO warnings at all are raised
230
+ >>> def clean_function():
231
+ ... pass
232
+ >>> with assert_no_warnings():
233
+ ... clean_function()
234
+
235
+ >>> # Only fail if warning message matches pattern
236
+ >>> def some_function():
237
+ ... warnings.warn("deprecated feature", FutureWarning)
238
+ >>> # Passes because warning contains "feature", not "other"
239
+ >>> with assert_no_warnings(FutureWarning, match="other"):
240
+ ... some_function()
241
+
242
+ Note:
243
+ This context manager is particularly useful in pytest for testing that refactored code properly uses new APIs
244
+ without triggering deprecation warnings.
245
+
246
+ """
247
+ with warnings.catch_warnings(record=True) as called:
248
+ # Cause all warnings to always be triggered.
249
+ warnings.simplefilter("always")
250
+ # Trigger a warning.
251
+ yield
252
+ # no warning raised
253
+ if not called:
254
+ return
255
+ if not warning_type:
256
+ raise AssertionError(f"While catching all warnings, these were found: {_warns_repr(called)}")
257
+ # filter warnings by type
258
+ warns = [w for w in called if issubclass(w.category, warning_type)]
259
+ # Verify some things
260
+ if not warns:
261
+ return
262
+ if not match:
263
+ raise AssertionError(
264
+ f"While catching `{warning_type.__name__}` warnings, these were found: {_warns_repr(warns)}"
265
+ )
266
+ found = [w for w in warns if match in w.message.__str__()]
267
+ if found:
268
+ raise AssertionError(
269
+ f'While catching `{warning_type.__name__}` warnings with "{match}",'
270
+ f" these were found: {_warns_repr(found)}"
271
+ )
272
+
273
+
274
+ class no_warning_call: # noqa: N801 - kept for backward compatibility with prior snake_case API
275
+ """Deprecated alias for :func:`~deprecate.utils.assert_no_warnings`.
276
+
277
+ This context manager is kept for backward compatibility so that existing imports like
278
+ ``from deprecate.utils import no_warning_call`` continue to work until v1.0.
279
+
280
+ Warning fires at instantiation — the ``no_warning_call(...)`` call line receives the
281
+ deprecation notice, regardless of how the context manager is subsequently used.
282
+
283
+ Args:
284
+ warning_type: The :class:`Warning` subclass to watch for. Defaults to :class:`Warning`
285
+ (all warning categories).
286
+ match: Optional substring that must appear in the warning message. When ``None`` (default),
287
+ any warning of the right category triggers an :class:`AssertionError`.
288
+
289
+ Examples:
290
+ >>> import warnings
291
+ >>> with warnings.catch_warnings():
292
+ ... warnings.simplefilter("ignore", DeprecationWarning)
293
+ ... with no_warning_call():
294
+ ... pass # no AssertionError means no warnings were emitted
295
+
296
+ """
297
+
298
+ def __init__(self, warning_type: Optional[type[Warning]] = None, match: Optional[str] = None) -> None:
299
+ """Emit the alias-deprecation warning and capture args for the no-warning assertion."""
300
+ warnings.warn(
301
+ "`deprecate.utils.no_warning_call` is deprecated in `0.6` and will be removed in `1.0`; "
302
+ "use `deprecate.utils.assert_no_warnings` instead.",
303
+ DeprecationWarning,
304
+ stacklevel=2,
305
+ )
306
+ self._warning_type = warning_type
307
+ self._match = match
308
+ self._inner: Any = None # ``assert_no_warnings`` returns a ``_GeneratorContextManager``
309
+
310
+ def __enter__(self) -> None:
311
+ """Enter the underlying ``assert_no_warnings`` context."""
312
+ self._inner = assert_no_warnings(warning_type=self._warning_type, match=self._match)
313
+ self._inner.__enter__()
314
+
315
+ def __exit__(
316
+ self,
317
+ exc_type: Optional[type[BaseException]],
318
+ exc_val: Optional[BaseException],
319
+ exc_tb: Optional[TracebackType],
320
+ ) -> Optional[bool]:
321
+ """Forward exit to the underlying ``assert_no_warnings`` so its AssertionError still surfaces."""
322
+ assert self._inner is not None # noqa: S101 — internal invariant: __exit__ only runs after __enter__
323
+ return self._inner.__exit__(exc_type, exc_val, exc_tb)
324
+
325
+
326
+ def void(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401
327
+ """Empty function that accepts any arguments and returns None.
328
+
329
+ This helper function is used to silence IDE warnings about unused parameters in deprecated functions where the
330
+ body is never executed (calls are forwarded to a target function). It's purely a convenience for developers.
331
+
332
+ Args:
333
+ *args: Any positional arguments (ignored).
334
+ **kwargs: Any keyword arguments (ignored).
335
+
336
+ Returns:
337
+ None always.
338
+
339
+ Example:
340
+ >>> from deprecate import deprecated, void
341
+ >>>
342
+ >>> def new_func(x: int) -> int:
343
+ ... return x * 2
344
+ >>>
345
+ >>> @deprecated(target=new_func, deprecated_in="1.0", remove_in="2.0")
346
+ ... def old_func(x: int) -> int:
347
+ ... void(x) # Silences IDE warning about unused 'x'
348
+ ... # This line is never reached - call forwarded to new_func
349
+
350
+ Note:
351
+ This function has no runtime effect - it's purely for developer convenience. You can also use ``pass`` or
352
+ just a docstring instead of calling ``void()``.
353
+
354
+ """
355
+ _, _ = args, kwargs
.venv/lib/python3.12/site-packages/distutils-precedence.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2638ce9e2500e572a5e0de7faed6661eb569d1b696fcba07b0dd223da5f5d224
3
+ size 151
.venv/lib/python3.12/site-packages/example.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #################################################################################
2
+ # Copyright (c) 2020, NVIDIA Corporation. All rights reserved. #
3
+ # #
4
+ # Redistribution and use in source and binary forms, with or without #
5
+ # modification, are permitted provided that the following conditions are met: #
6
+ # #
7
+ # * Redistributions of source code must retain the above copyright notice, #
8
+ # this list of conditions and the following disclaimer. #
9
+ # * Redistributions in binary form must reproduce the above copyright #
10
+ # notice, this list of conditions and the following disclaimer in the #
11
+ # documentation and/or other materials provided with the distribution. #
12
+ # * Neither the name of the NVIDIA Corporation nor the names of its #
13
+ # contributors may be used to endorse or promote products derived from #
14
+ # this software without specific prior written permission. #
15
+ # #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF #
26
+ # THE POSSIBILITY OF SUCH DAMAGE. #
27
+ #################################################################################
28
+
29
+ #
30
+ # Sample script to demonstrate the usage of NVML API python bindings
31
+ #
32
+
33
+ # To Run:
34
+ # $ python ./example.py
35
+
36
+ from pynvml import *
37
+
38
+ #
39
+ # Helper function
40
+ #
41
+ def StrVirt(mode):
42
+ if mode == NVML_GPU_VIRTUALIZATION_MODE_NONE:
43
+ return "None";
44
+ elif mode == NVML_GPU_VIRTUALIZATION_MODE_PASSTHROUGH:
45
+ return "Pass-Through";
46
+ elif mode == NVML_GPU_VIRTUALIZATION_MODE_VGPU:
47
+ return "VGPU";
48
+ elif mode == NVML_GPU_VIRTUALIZATION_MODE_HOST_VGPU:
49
+ return "Host VGPU";
50
+ elif mode == NVML_GPU_VIRTUALIZATION_MODE_HOST_VSGA:
51
+ return "Host VSGA";
52
+ else:
53
+ return "Unknown";
54
+
55
+ #
56
+ # Converts errors into string messages
57
+ #
58
+ def handleError(err):
59
+ if (err.value == NVML_ERROR_NOT_SUPPORTED):
60
+ return "N/A"
61
+ else:
62
+ return err.__str__()
63
+
64
+ #######
65
+ def deviceQuery():
66
+
67
+ strResult = ''
68
+ try:
69
+ #
70
+ # Initialize NVML
71
+ #
72
+ nvmlInit()
73
+
74
+ strResult += ' <driver_version>' + str(nvmlSystemGetDriverVersion()) + '</driver_version>\n'
75
+
76
+ deviceCount = nvmlDeviceGetCount()
77
+ strResult += ' <attached_gpus>' + str(deviceCount) + '</attached_gpus>\n'
78
+
79
+ for i in range(0, deviceCount):
80
+ handle = nvmlDeviceGetHandleByIndex(i)
81
+
82
+ pciInfo = nvmlDeviceGetPciInfo(handle)
83
+
84
+ strResult += ' <gpu id="%s">\n' % pciInfo.busId
85
+
86
+ strResult += ' <product_name>' + nvmlDeviceGetName(handle) + '</product_name>\n'
87
+
88
+ brandNames = {NVML_BRAND_UNKNOWN : "Unknown",
89
+ NVML_BRAND_QUADRO : "Quadro",
90
+ NVML_BRAND_TESLA : "Tesla",
91
+ NVML_BRAND_NVS : "NVS",
92
+ NVML_BRAND_GRID : "Grid",
93
+ NVML_BRAND_TITAN : "Titan",
94
+ NVML_BRAND_GEFORCE : "GeForce",
95
+ NVML_BRAND_NVIDIA_VAPPS : "NVIDIA Virtual Applications",
96
+ NVML_BRAND_NVIDIA_VPC : "NVIDIA Virtual PC",
97
+ NVML_BRAND_NVIDIA_VCS : "NVIDIA vGPU for Compute",
98
+ NVML_BRAND_NVIDIA_VWS : "NVIDIA RTX Virtual Workstation",
99
+ NVML_BRAND_NVIDIA_CLOUD_GAMING : "NVIDIA Cloud Gaming",
100
+ NVML_BRAND_QUADRO_RTX : "Quadro RTX",
101
+ NVML_BRAND_NVIDIA_RTX : "NVIDIA RTX",
102
+ NVML_BRAND_NVIDIA : "NVIDIA",
103
+ NVML_BRAND_GEFORCE_RTX : "GeForce RTX",
104
+ NVML_BRAND_TITAN_RTX : "TITAN RTX",
105
+
106
+ }
107
+
108
+ try:
109
+ # If nvmlDeviceGetBrand() succeeds it is guaranteed to be in the dictionary
110
+ brandName = brandNames[nvmlDeviceGetBrand(handle)]
111
+ except NVMLError as err:
112
+ brandName = handleError(err)
113
+
114
+ strResult += ' <product_brand>' + brandName + '</product_brand>\n'
115
+
116
+ try:
117
+ serial = nvmlDeviceGetSerial(handle)
118
+ except NVMLError as err:
119
+ serial = handleError(err)
120
+
121
+ strResult += ' <serial>' + serial + '</serial>\n'
122
+
123
+ try:
124
+ uuid = nvmlDeviceGetUUID(handle)
125
+ except NVMLError as err:
126
+ uuid = handleError(err)
127
+
128
+ strResult += ' <uuid>' + uuid + '</uuid>\n'
129
+
130
+ strResult += ' <gpu_virtualization_mode>\n'
131
+ try:
132
+ mode = StrVirt(nvmlDeviceGetVirtualizationMode(handle))
133
+ except NVMLError as err:
134
+ mode = handleError(err)
135
+ strResult += ' <virtualization_mode>' + mode + '</virtualization_mode>\n'
136
+ strResult += ' </gpu_virtualization_mode>\n'
137
+
138
+ try:
139
+ gridLicensableFeatures = nvmlDeviceGetGridLicensableFeatures(handle)
140
+ if gridLicensableFeatures.isGridLicenseSupported == 1:
141
+ strResult += ' <vgpu_software_licensed_product>\n'
142
+ for i in range(gridLicensableFeatures.licensableFeaturesCount):
143
+ if gridLicensableFeatures.gridLicensableFeatures[i].featureState == 0:
144
+ if nvmlDeviceGetVirtualizationMode(handle) == NVML_GPU_VIRTUALIZATION_MODE_PASSTHROUGH:
145
+ strResult += ' <licensed_product_name>' + 'NVIDIA Virtual Applications' + '</licensed_product_name>\n'
146
+ strResult += ' <license_status>' + 'Licensed' + '</license_status>\n'
147
+ else:
148
+ strResult += ' <licensed_product_name>' + gridLicensableFeatures.gridLicensableFeatures[i].productName + '</licensed_product_name>\n'
149
+ strResult += ' <license_status>' + 'Unlicensed' + '</license_status>\n'
150
+ else:
151
+ strResult += ' <licensed_product_name>' + gridLicensableFeatures.gridLicensableFeatures[i].productName + '</licensed_product_name>\n'
152
+ strResult += ' <license_status>' + 'Licensed' + '</license_status>\n'
153
+ strResult += ' </vgpu_software_licensed_product>\n'
154
+ except NVMLError as err:
155
+ gridLicensableFeatures = handleError(err)
156
+
157
+ strResult += ' </gpu>\n'
158
+
159
+ except NVMLError as err:
160
+ strResult += 'example.py: ' + err.__str__() + '\n'
161
+
162
+ nvmlShutdown()
163
+
164
+ return strResult
165
+
166
+ # If this is not exectued when module is imported
167
+ if __name__ == "__main__":
168
+ print(deviceQuery())
169
+
.venv/lib/python3.12/site-packages/filelock-3.32.3.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv/lib/python3.12/site-packages/filelock-3.32.3.dist-info/METADATA ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.5
2
+ Name: filelock
3
+ Version: 3.32.3
4
+ Summary: A platform independent file lock.
5
+ Project-URL: Documentation, https://py-filelock.readthedocs.io
6
+ Project-URL: Homepage, https://github.com/tox-dev/py-filelock
7
+ Project-URL: Source, https://github.com/tox-dev/py-filelock
8
+ Project-URL: Tracker, https://github.com/tox-dev/py-filelock/issues
9
+ Maintainer-email: Bernát Gábor <gaborjbernat@gmail.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: application,cache,directory,log,user
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Programming Language :: Python :: 3.15
25
+ Classifier: Topic :: Internet
26
+ Classifier: Topic :: Software Development :: Libraries
27
+ Classifier: Topic :: System
28
+ Requires-Python: >=3.10
29
+ Description-Content-Type: text/markdown
30
+
31
+ # filelock
32
+
33
+ [![PyPI](https://img.shields.io/pypi/v/filelock)](https://pypi.org/project/filelock/)
34
+ [![Supported Python versions](https://img.shields.io/pypi/pyversions/filelock.svg)](https://pypi.org/project/filelock/)
35
+ [![Documentation status](https://readthedocs.org/projects/py-filelock/badge/?version=latest)](https://py-filelock.readthedocs.io/en/latest/?badge=latest)
36
+ [![Downloads](https://static.pepy.tech/badge/filelock/month)](https://pepy.tech/project/filelock)
37
+ [![check](https://github.com/tox-dev/py-filelock/actions/workflows/check.yaml/badge.svg)](https://github.com/tox-dev/py-filelock/actions/workflows/check.yaml)
38
+
39
+ For more information checkout the [official documentation](https://py-filelock.readthedocs.io/en/latest/index.html).
.venv/lib/python3.12/site-packages/filelock-3.32.3.dist-info/RECORD ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ filelock-3.32.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ filelock-3.32.3.dist-info/METADATA,sha256=LYD0O9kFaJFFwAsxM7yViV1lTO1wqWoYAukjfg1mWZ8,2028
3
+ filelock-3.32.3.dist-info/RECORD,,
4
+ filelock-3.32.3.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
5
+ filelock-3.32.3.dist-info/licenses/LICENSE,sha256=YIyJ1QYK6ZIa3M8yNmlbxlSplG4SMj72wCHfoE4pTUg,1088
6
+ filelock/__init__.py,sha256=ZEhX0CozvRxFQwsm8YYc6uiLvuIYe-aoD20ACfjyizg,3469
7
+ filelock/__pycache__/__init__.cpython-312.pyc,,
8
+ filelock/__pycache__/_api.cpython-312.pyc,,
9
+ filelock/__pycache__/_async.cpython-312.pyc,,
10
+ filelock/__pycache__/_async_read_write.cpython-312.pyc,,
11
+ filelock/__pycache__/_descriptor.cpython-312.pyc,,
12
+ filelock/__pycache__/_error.cpython-312.pyc,,
13
+ filelock/__pycache__/_identity.cpython-312.pyc,,
14
+ filelock/__pycache__/_lease.cpython-312.pyc,,
15
+ filelock/__pycache__/_marker.cpython-312.pyc,,
16
+ filelock/__pycache__/_read_write.cpython-312.pyc,,
17
+ filelock/__pycache__/_soft.cpython-312.pyc,,
18
+ filelock/__pycache__/_soft_protocol.cpython-312.pyc,,
19
+ filelock/__pycache__/_strict.cpython-312.pyc,,
20
+ filelock/__pycache__/_unix.cpython-312.pyc,,
21
+ filelock/__pycache__/_util.cpython-312.pyc,,
22
+ filelock/__pycache__/_windows.cpython-312.pyc,,
23
+ filelock/__pycache__/asyncio.cpython-312.pyc,,
24
+ filelock/__pycache__/version.cpython-312.pyc,,
25
+ filelock/_api.py,sha256=VWiuW2oWHrM9Fy3yRlsxre-daXjpmzCbJO43iFuYkJE,82436
26
+ filelock/_async.py,sha256=rO6gt1h6ZvT2gw_0P1Xmf1jZs82kEipZ9xX4_rJUm3k,6111
27
+ filelock/_async_read_write.py,sha256=ZAJJ02CALgZ6uhhWew4DefTtnEU7lslSoG-VjmMpDBs,13325
28
+ filelock/_descriptor.py,sha256=ss1FfyEAyrZ1QB3LDXUtJHk5ZFAfSAaCdaa5Yp1Vzk4,2981
29
+ filelock/_error.py,sha256=SfdLwQeooh81jIM1S4d1010ctZzXZBYBo78bJA1lEZs,2699
30
+ filelock/_identity.py,sha256=dY_ngMJQJHm0fLD5TaGef12oOGeBAl9h0_7Xv1d3GMM,8415
31
+ filelock/_lease.py,sha256=nEi4I02Ry3t8QSLYcctr36XV4jV6eLyaTyHo6zBeSKE,15152
32
+ filelock/_marker.py,sha256=7VJWyyrh8wW8VywSTLLIR7OC__aNUn4zFnel5JdQwWI,6026
33
+ filelock/_read_write.py,sha256=PBlLg_fbkqDcpRyJ5NkZgoWLR9DEUHM-1sQzBnZsOD8,32881
34
+ filelock/_soft.py,sha256=ydpW15r3gGW2kBaHhj8FvnATQw5-kfXnSWyYhbEQNKA,13014
35
+ filelock/_soft_protocol.py,sha256=qEM2x9Nz9zguXwwWjZsCsPEfas5nqHlJ-_oHvAM0Uo4,187
36
+ filelock/_soft_rw/__init__.py,sha256=_ktpGmVObzrvL0K1_EAV3LF7B9JarYxW-mx_eyGPhT0,370
37
+ filelock/_soft_rw/__pycache__/__init__.cpython-312.pyc,,
38
+ filelock/_soft_rw/__pycache__/_async.cpython-312.pyc,,
39
+ filelock/_soft_rw/__pycache__/_sync.cpython-312.pyc,,
40
+ filelock/_soft_rw/_async.py,sha256=oKDt9jgsRSAvx2ls9cA0AN2Lk0WlHc7bdmKTTCNjl9g,11492
41
+ filelock/_soft_rw/_sync.py,sha256=XMC0kMoRBMoCAJqxK9bU_UW5o0KVQ5UmcdYqpp5j8kM,43201
42
+ filelock/_strict.py,sha256=N5037nWAz2AF59LlyPMsOg4IwGL13D6x64hhQEn3vQQ,38823
43
+ filelock/_unix.py,sha256=W95gKLjYivNZYLT3634o7l0pQfvU8SdBW_2C3bo3lLw,8722
44
+ filelock/_util.py,sha256=gY839OXIttp1JOr9-FuhLTYYOoBtExkB2Nn50t8oxYQ,6356
45
+ filelock/_windows.py,sha256=sLAk--cnOK1f-9RTuAAAOSjh4XBcxa0R3jy2w3XgUZs,15988
46
+ filelock/asyncio.py,sha256=iE593J-CgUl3yAAGsnzitId4MtHDs5ne--F8N8oS6ys,34599
47
+ filelock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
48
+ filelock/version.py,sha256=7xrb9cafe38S02w7EZcEpqTbiGOe0tDHHrLpKSH8XgM,522
.venv/lib/python3.12/site-packages/filelock-3.32.3.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.venv/lib/python3.12/site-packages/filelock-3.32.3.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Bernát Gábor and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
.venv/lib/python3.12/site-packages/filelock/__init__.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A platform independent file lock that supports the with-statement.
3
+
4
+ .. autodata:: filelock.__version__
5
+ :no-value:
6
+
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ import warnings
13
+ from typing import TYPE_CHECKING, Final
14
+
15
+ from ._api import AcquireReturnProxy, BaseFileLock, CloseErrorPolicy, ContextErrorPolicy, LockOptions
16
+ from ._descriptor import lock_descriptor, unlock_descriptor
17
+ from ._error import LeaseSettingsMismatch, SoftFileLockLifetimeWarning, SoftFileLockProtocolError, Timeout
18
+ from ._lease import LeaseCompromise, SoftFileLease
19
+ from ._marker import MarkerSoftFileLock, OwnerRecord
20
+
21
+ if TYPE_CHECKING:
22
+ from ._async_read_write import (
23
+ AsyncAcquireReadWriteReturnProxy,
24
+ AsyncReadWriteLock,
25
+ )
26
+ from ._read_write import ReadWriteLock
27
+ else:
28
+ try:
29
+ from ._async_read_write import AsyncAcquireReadWriteReturnProxy, AsyncReadWriteLock
30
+ from ._read_write import ReadWriteLock
31
+ except ImportError: # pragma: lacks sqlite3
32
+ AsyncAcquireReadWriteReturnProxy = None
33
+ AsyncReadWriteLock = None
34
+ ReadWriteLock = None
35
+
36
+ from ._soft import SoftFileLock
37
+ from ._soft_rw import AsyncAcquireSoftReadWriteReturnProxy, AsyncSoftReadWriteLock, SoftReadWriteLock
38
+ from ._strict import StrictSoftFileClaim, StrictSoftFileClaimState, StrictSoftFileLock
39
+ from ._unix import UnixFileLock, has_fcntl
40
+ from ._windows import WindowsFileLock
41
+ from .asyncio import (
42
+ AsyncAcquireReturnProxy,
43
+ AsyncSoftFileLease,
44
+ AsyncSoftFileLock,
45
+ AsyncStrictSoftFileLock,
46
+ AsyncUnixFileLock,
47
+ AsyncWindowsFileLock,
48
+ BaseAsyncFileLock,
49
+ )
50
+ from .version import version
51
+
52
+ #: version of the project as a string
53
+ __version__: Final[str] = version
54
+
55
+
56
+ if sys.platform == "win32": # pragma: win32 cover
57
+ _FileLock: type[BaseFileLock] = WindowsFileLock
58
+ _AsyncFileLock: type[BaseAsyncFileLock] = AsyncWindowsFileLock
59
+ else: # pragma: win32 no cover # ruff:ignore[collapsible-else-if] # the else carries the win32 no-cover pragma
60
+ if has_fcntl:
61
+ _FileLock: type[BaseFileLock] = UnixFileLock
62
+ _AsyncFileLock: type[BaseAsyncFileLock] = AsyncUnixFileLock
63
+ else:
64
+ _FileLock = SoftFileLock
65
+ _AsyncFileLock = AsyncSoftFileLock
66
+ warnings.warn("only soft file lock is available", stacklevel=2)
67
+
68
+ if TYPE_CHECKING:
69
+ FileLock = SoftFileLock
70
+ AsyncFileLock = AsyncSoftFileLock
71
+ else:
72
+ #: Alias for the lock, which should be used for the current platform.
73
+ FileLock = _FileLock
74
+ AsyncFileLock = _AsyncFileLock
75
+
76
+
77
+ __all__ = [
78
+ "AcquireReturnProxy",
79
+ "AsyncAcquireReadWriteReturnProxy",
80
+ "AsyncAcquireReturnProxy",
81
+ "AsyncAcquireSoftReadWriteReturnProxy",
82
+ "AsyncFileLock",
83
+ "AsyncReadWriteLock",
84
+ "AsyncSoftFileLease",
85
+ "AsyncSoftFileLock",
86
+ "AsyncSoftReadWriteLock",
87
+ "AsyncStrictSoftFileLock",
88
+ "AsyncUnixFileLock",
89
+ "AsyncWindowsFileLock",
90
+ "BaseAsyncFileLock",
91
+ "BaseFileLock",
92
+ "CloseErrorPolicy",
93
+ "ContextErrorPolicy",
94
+ "FileLock",
95
+ "LeaseCompromise",
96
+ "LeaseSettingsMismatch",
97
+ "LockOptions",
98
+ "MarkerSoftFileLock",
99
+ "OwnerRecord",
100
+ "ReadWriteLock",
101
+ "SoftFileLease",
102
+ "SoftFileLock",
103
+ "SoftFileLockLifetimeWarning",
104
+ "SoftFileLockProtocolError",
105
+ "SoftReadWriteLock",
106
+ "StrictSoftFileClaim",
107
+ "StrictSoftFileClaimState",
108
+ "StrictSoftFileLock",
109
+ "Timeout",
110
+ "UnixFileLock",
111
+ "WindowsFileLock",
112
+ "__version__",
113
+ "lock_descriptor",
114
+ "unlock_descriptor",
115
+ ]
.venv/lib/python3.12/site-packages/filelock/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (2.74 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_api.cpython-312.pyc ADDED
Binary file (89.6 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_async.cpython-312.pyc ADDED
Binary file (8.44 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_async_read_write.cpython-312.pyc ADDED
Binary file (18 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_descriptor.cpython-312.pyc ADDED
Binary file (3.43 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_error.cpython-312.pyc ADDED
Binary file (4.47 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_identity.cpython-312.pyc ADDED
Binary file (8.87 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_lease.cpython-312.pyc ADDED
Binary file (16 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_marker.cpython-312.pyc ADDED
Binary file (7.39 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_read_write.cpython-312.pyc ADDED
Binary file (39.9 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_soft.cpython-312.pyc ADDED
Binary file (13.2 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_soft_protocol.cpython-312.pyc ADDED
Binary file (418 Bytes). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_strict.cpython-312.pyc ADDED
Binary file (44.1 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_unix.cpython-312.pyc ADDED
Binary file (9.17 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_util.cpython-312.pyc ADDED
Binary file (6.47 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/_windows.cpython-312.pyc ADDED
Binary file (16.5 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/asyncio.cpython-312.pyc ADDED
Binary file (37.5 kB). View file
 
.venv/lib/python3.12/site-packages/filelock/__pycache__/version.cpython-312.pyc ADDED
Binary file (637 Bytes). View file
 
.venv/lib/python3.12/site-packages/filelock/_api.py ADDED
@@ -0,0 +1,1826 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import inspect
5
+ import logging
6
+ import math
7
+ import os
8
+ import secrets
9
+ import sys
10
+ import time
11
+ import warnings
12
+ from abc import ABCMeta, abstractmethod
13
+ from collections.abc import Callable, Hashable
14
+ from contextlib import contextmanager
15
+ from dataclasses import dataclass
16
+ from itertools import count, starmap
17
+ from threading import Condition, RLock, get_ident, local
18
+ from typing import TYPE_CHECKING, Final, Literal, NoReturn, TypedDict, TypeVar, cast
19
+ from weakref import WeakKeyDictionary, WeakValueDictionary
20
+
21
+ from ._error import SoftFileLockLifetimeWarning, Timeout
22
+ from ._util import break_lock_file
23
+
24
+ #: No explicit file permission mode was passed. Lock files then open with 0o666 so umask and default ACLs pick
25
+ #: the final permissions, and fchmod is skipped to preserve POSIX default ACL inheritance.
26
+ _UNSET_FILE_MODE: Final[int] = -1
27
+
28
+ #: Ceiling on the retry counter used as a power of two, so a long contended wait cannot overflow the backoff multiply.
29
+ _MAX_BACKOFF_EXPONENT: Final[int] = 20
30
+
31
+ #: How a context manager reconciles a body failure with a release failure on exit (see the property of this name).
32
+ ContextErrorPolicy = Literal["chain", "group"]
33
+ _CONTEXT_ERROR_POLICIES: Final[frozenset[str]] = frozenset({"chain", "group"})
34
+
35
+ #: What a descriptor-owning backend does with an ``os.close`` failure after relinquishing ownership (see the property).
36
+ CloseErrorPolicy = Literal["default", "raise", "suppress"]
37
+ _CLOSE_ERROR_POLICIES: Final[frozenset[str]] = frozenset({"default", "raise", "suppress"})
38
+
39
+ if TYPE_CHECKING:
40
+ from collections.abc import Generator
41
+ from types import TracebackType
42
+ from typing import Protocol
43
+
44
+ from _typeshed import Unused
45
+
46
+ from ._read_write import ReadWriteLock
47
+ from ._soft_rw import SoftReadWriteLock
48
+
49
+ class _ForkResettable(Protocol):
50
+ def _reset_after_fork_in_child(self) -> None: ...
51
+
52
+ class _ForkDescriptorOwner(Protocol):
53
+ def _descriptors_for_fork(self) -> tuple[tuple[int, tuple[int, int] | None], ...]: ...
54
+
55
+ # Matched against the class object itself rather than `type[...]` of it. A metaclass supplies this method to the
56
+ # class while leaving instances without it, so a `type[_ForkResettableClass]` bound rejects `ReadWriteLock`.
57
+ class _ForkResettableClass(Protocol):
58
+ def _reset_class_after_fork(self) -> None: ...
59
+
60
+ class _RegisterAtFork(Protocol):
61
+ def __call__(
62
+ self,
63
+ *,
64
+ before: Callable[[], None] | None = None,
65
+ after_in_parent: Callable[[], None] | None = None,
66
+ after_in_child: Callable[[], None] | None = None,
67
+ ) -> None: ...
68
+
69
+ if sys.version_info >= (3, 11): # pragma: no cover (py311+)
70
+ from typing import Self
71
+ else: # pragma: no cover (<py311)
72
+ from typing_extensions import Self
73
+
74
+ _LOGGER: Final[logging.Logger] = logging.getLogger("filelock")
75
+ _REGISTER_AT_FORK: Final[_RegisterAtFork | None] = cast("_RegisterAtFork | None", getattr(os, "register_at_fork", None))
76
+ _HAS_REGISTER_AT_FORK: Final[bool] = _REGISTER_AT_FORK is not None
77
+
78
+ _ExtraValue = TypeVar("_ExtraValue")
79
+ _MarkerValue = TypeVar("_MarkerValue")
80
+ _SubclassValue = TypeVar("_SubclassValue")
81
+ _LockInitValue = float | int | bool | str | None | Callable[[int], None]
82
+
83
+
84
+ class LockOptions(TypedDict, total=False):
85
+ """Every option the metaclass forwards, so a subclass adding its own can still type what it passes through."""
86
+
87
+ timeout: float
88
+ mode: int
89
+ thread_local: bool
90
+ blocking: bool
91
+ is_singleton: bool
92
+ poll_interval: float
93
+ lifetime: float | None
94
+ context_error_policy: ContextErrorPolicy
95
+ close_error_policy: CloseErrorPolicy
96
+ fallback_to_soft: bool
97
+ preserve_lock_file: bool
98
+ on_acquired: Callable[[int], None] | None
99
+
100
+
101
+ def _exception_group_cls() -> type[BaseException]:
102
+ # BaseExceptionGroup is a builtin on 3.11+; on 3.10 it needs the exceptiongroup backport. filelock keeps zero
103
+ # runtime dependencies, so the backport is imported lazily rather than required, and only group mode needs it.
104
+ if sys.version_info >= (3, 11): # pragma: no cover (py311+)
105
+ return BaseExceptionGroup # ruff:ignore[undefined-name] # builtin on 3.11+
106
+ # Alias the import so BaseExceptionGroup above stays the builtin rather than an unbound local of this function.
107
+ from exceptiongroup import ( # ruff:ignore[import-outside-top-level] # pragma: no cover (<py311)
108
+ BaseExceptionGroup as _Backport,
109
+ )
110
+
111
+ return _Backport # pragma: no cover (<py311)
112
+
113
+
114
+ def _raise_grouped_errors(
115
+ message: str,
116
+ first_error: BaseException,
117
+ second_error: BaseException,
118
+ *additional_errors: BaseException,
119
+ marker: tuple[str, _MarkerValue] | None = None,
120
+ ) -> NoReturn:
121
+ errors = (first_error, second_error, *additional_errors)
122
+ _detach_grouped_contexts(errors)
123
+ group = _exception_group_cls()(message, errors)
124
+ if marker is not None:
125
+ setattr(group, marker[0], marker[1])
126
+ raise group from None
127
+
128
+
129
+ def _detach_grouped_contexts(errors: tuple[BaseException, ...]) -> None:
130
+ seen: set[int] = set()
131
+ pending = list(errors)
132
+ while pending:
133
+ error = pending.pop()
134
+ if id(error) in seen:
135
+ continue
136
+ seen.add(id(error))
137
+ if (context := error.__context__) is not None and (
138
+ context is error
139
+ or _same_exception_tree(error, context)
140
+ or any(context is root or _contains_exception(root, context) for root in errors)
141
+ ):
142
+ error.__context__ = None
143
+ elif context is not None:
144
+ pending.append(context)
145
+ if error.__cause__ is not None:
146
+ pending.append(error.__cause__)
147
+ if isinstance(error, _exception_group_cls()):
148
+ pending.extend(cast("_ExceptionGroupProtocol", error).exceptions)
149
+
150
+
151
+ def _same_exception_tree(first: BaseException, second: BaseException) -> bool:
152
+ pending = [(first, second)]
153
+ seen: set[tuple[int, int]] = set()
154
+ while pending:
155
+ first_error, second_error = pending.pop()
156
+ if first_error is second_error:
157
+ continue
158
+ if (pair := (id(first_error), id(second_error))) in seen:
159
+ continue
160
+ seen.add(pair)
161
+ if (
162
+ type(first_error) is not type(second_error)
163
+ or not isinstance(first_error, _exception_group_cls())
164
+ or not isinstance(second_error, _exception_group_cls())
165
+ ):
166
+ return False
167
+ first_group = cast("_ExceptionGroupProtocol", first_error)
168
+ second_group = cast("_ExceptionGroupProtocol", second_error)
169
+ if first_group.message != second_group.message or len(first_group.exceptions) != len(second_group.exceptions):
170
+ return False
171
+ pending.extend(zip(first_group.exceptions, second_group.exceptions, strict=True))
172
+ return True
173
+
174
+
175
+ def _contains_exception(error: BaseException, target: BaseException | None) -> bool:
176
+ if target is None or not isinstance(error, _exception_group_cls()):
177
+ return False
178
+ pending = list(cast("_ExceptionGroupProtocol", error).exceptions)
179
+ seen: set[int] = set()
180
+ while pending:
181
+ child = pending.pop()
182
+ if child is target:
183
+ return True
184
+ if id(child) in seen:
185
+ continue
186
+ seen.add(id(child))
187
+ if isinstance(child, _exception_group_cls()):
188
+ pending.extend(cast("_ExceptionGroupProtocol", child).exceptions)
189
+ return False
190
+
191
+
192
+ def _append_exception_context(error: BaseException, context: BaseException) -> None:
193
+ if _exception_graph_contains(error, context) or _exception_graph_contains(context, error):
194
+ return
195
+ if error.__context__ is None:
196
+ error.__context__ = context
197
+ return
198
+ tail = error
199
+ seen: set[int] = set()
200
+ while id(tail) not in seen:
201
+ seen.add(id(tail))
202
+ if (next_error := tail.__cause__ if tail.__cause__ is not None else tail.__context__) is None:
203
+ tail.__context__ = context
204
+ return
205
+ tail = next_error
206
+
207
+
208
+ def _exception_graph_contains(error: BaseException, target: BaseException) -> bool:
209
+ pending = [error]
210
+ seen: set[int] = set()
211
+ while pending:
212
+ current = pending.pop()
213
+ if current is target:
214
+ return True
215
+ if id(current) in seen: # pragma: no cover - arbitrary caller exceptions can contain cycles
216
+ continue
217
+ seen.add(id(current))
218
+ if current.__cause__ is not None:
219
+ pending.append(current.__cause__)
220
+ if current.__context__ is not None:
221
+ pending.append(current.__context__)
222
+ if isinstance(current, _exception_group_cls()):
223
+ pending.extend(cast("_ExceptionGroupProtocol", current).exceptions)
224
+ return False
225
+
226
+
227
+ def _grouped_errors(
228
+ error: BaseException, message: str, marker: tuple[str, _MarkerValue]
229
+ ) -> tuple[BaseException, ...] | None:
230
+ if not isinstance(error, _exception_group_cls()):
231
+ return None
232
+ group = cast("_ExceptionGroupProtocol", error)
233
+ return group.exceptions if group.message == message and getattr(group, marker[0], None) is marker[1] else None
234
+
235
+
236
+ if TYPE_CHECKING:
237
+
238
+ class _ExceptionGroupProtocol(Protocol):
239
+ @property
240
+ def message(self) -> str: ...
241
+
242
+ @property
243
+ def exceptions(self) -> tuple[BaseException, ...]: ...
244
+
245
+
246
+ def _raise_chained_errors(first_error: BaseException, second_error: BaseException | None = None) -> NoReturn:
247
+ if second_error is None:
248
+ first_context = first_error.__context__
249
+ try:
250
+ raise first_error # ruff:ignore[raise-within-try] # the handler restores caller-supplied context before propagation
251
+ except BaseException:
252
+ first_error.__context__ = first_context
253
+ raise
254
+ if (second_context := second_error.__context__) is not None and second_context is not first_error:
255
+ _detach_exception_context(second_context, first_error)
256
+ _append_exception_context(first_error, second_context)
257
+ first_context = first_error.__context__
258
+ try:
259
+ raise first_error # ruff:ignore[raise-within-try] # the second raise needs this error as implicit context
260
+ except BaseException: # ruff:ignore[blind-except] # first_error may be a control-flow exception
261
+ first_error.__context__ = first_context
262
+ try:
263
+ raise second_error # ruff:ignore[raise-within-try] # the handler makes the chain interpreter-independent
264
+ except BaseException:
265
+ second_error.__context__ = first_error
266
+ first_error.__context__ = first_context
267
+ raise
268
+
269
+
270
+ def _detach_exception_context(error: BaseException, target: BaseException) -> None:
271
+ pending = [error]
272
+ seen: set[int] = set()
273
+ while pending:
274
+ current = pending.pop()
275
+ if id(current) in seen:
276
+ continue
277
+ seen.add(id(current))
278
+ if current.__context__ is target:
279
+ current.__context__ = None
280
+ elif current.__context__ is not None:
281
+ pending.append(current.__context__)
282
+ if current.__cause__ is not None:
283
+ pending.append(current.__cause__)
284
+ if isinstance(current, _exception_group_cls()):
285
+ pending.extend(cast("_ExceptionGroupProtocol", current).exceptions)
286
+
287
+
288
+ def _raise_body_and_release(body_error: BaseException, release_error: BaseException) -> NoReturn:
289
+ # Group mode: surface the body failure and the release failure as sibling leaves instead of letting one hide in the
290
+ # other's __context__. BaseExceptionGroup returns a plain ExceptionGroup when both leaves subclass Exception, so
291
+ # ``except*`` and ``except Exception`` still catch them; a BaseException leaf (KeyboardInterrupt, CancelledError)
292
+ # keeps the group outside ordinary handlers. ``from None`` stops the group itself gaining a redundant __context__.
293
+ _raise_grouped_errors("lock body and release both failed", body_error, release_error)
294
+
295
+
296
+ def _raise_cleanup_errors(
297
+ message: str,
298
+ primary_error: BaseException,
299
+ *cleanup_errors: BaseException | None,
300
+ ) -> NoReturn:
301
+ _raise_grouped_errors(
302
+ message,
303
+ primary_error,
304
+ *(error for error in cleanup_errors if error is not None),
305
+ )
306
+
307
+
308
+ # On Windows os.path.realpath calls CreateFileW with share_mode=0, which blocks concurrent DeleteFileW and causes
309
+ # livelocks under threaded contention with SoftFileLock. os.path.abspath is purely string-based and avoids this.
310
+ _resolve_dir: Final[Callable[[str], str]] = os.path.abspath if sys.platform == "win32" else os.path.realpath
311
+
312
+
313
+ def _canonical(path: str | os.PathLike[str]) -> str:
314
+ """
315
+ Return one stable key for *path*, collapsing equivalent spellings without following a final symlink.
316
+
317
+ Relative, absolute, and ``./`` spellings of one lock file must map to a single singleton instance, deadlock-registry
318
+ entry, and removal key. Resolving the whole path with ``realpath`` would follow a final symlink and alias a lock
319
+ target the backend deliberately rejects, so the registry identity would differ from the backend's. Resolving only
320
+ the parent directory and re-appending the literal final component collapses the equivalent spellings while keeping a
321
+ final symlink a distinct key. On Windows the parent is resolved with ``abspath`` so junctions and reparse points are
322
+ not followed either.
323
+ """
324
+ parent, name = os.path.split(os.fspath(path))
325
+ return os.path.join(_resolve_dir(parent or os.curdir), name) # ruff:ignore[os-path-join] # string join matches abspath/realpath
326
+
327
+
328
+ class _ThreadLocalRegistry(local):
329
+ def __init__(self) -> None:
330
+ super().__init__()
331
+ self.held: dict[Hashable, int] = {}
332
+
333
+
334
+ _registry: Final[_ThreadLocalRegistry] = _ThreadLocalRegistry()
335
+
336
+
337
+ _T = TypeVar("_T", bound="BaseFileLock")
338
+
339
+
340
+ class FileLockMeta(ABCMeta):
341
+ _instances: WeakValueDictionary[str, BaseFileLock]
342
+ _instances_lock: RLock
343
+ _instances_under_construction: set[str]
344
+
345
+ def __call__( # ruff:ignore[too-many-arguments] # forwards the public constructor's documented parameters
346
+ cls: type[_T],
347
+ lock_file: str | os.PathLike[str],
348
+ timeout: float = -1,
349
+ mode: int = _UNSET_FILE_MODE,
350
+ thread_local: bool = True, # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility
351
+ *,
352
+ blocking: bool = True,
353
+ is_singleton: bool = False,
354
+ poll_interval: float = 0.05,
355
+ lifetime: float | None = None,
356
+ context_error_policy: ContextErrorPolicy = "chain",
357
+ close_error_policy: CloseErrorPolicy = "default",
358
+ fallback_to_soft: bool = True,
359
+ preserve_lock_file: bool = False,
360
+ on_acquired: Callable[[int], None] | None = None,
361
+ **kwargs: _ExtraValue,
362
+ ) -> _T:
363
+ _ensure_current_process()
364
+ lifetime = _resolve_lifetime(lifetime, cls, stacklevel=cls._constructor_lifetime_warning_stacklevel)
365
+ # Validate before building the instance: a raise inside __init__ would leave a half-constructed object whose
366
+ # __del__ then trips over the missing context.
367
+ context_error_policy = _resolve_context_error_policy(context_error_policy)
368
+ close_error_policy = _resolve_close_error_policy(close_error_policy)
369
+ preserve_lock_file = _resolve_preserve_lock_file(
370
+ preserve=preserve_lock_file, supported=cls._preserve_lock_file_supported, cls_name=cls.__name__
371
+ )
372
+ on_acquired = _resolve_on_acquired(on_acquired, supported=cls._on_acquired_supported, cls_name=cls.__name__)
373
+ params: dict[str, _LockInitValue | _ExtraValue] = {
374
+ "timeout": timeout,
375
+ "mode": mode,
376
+ "thread_local": thread_local,
377
+ "blocking": blocking,
378
+ "is_singleton": is_singleton,
379
+ "poll_interval": poll_interval,
380
+ "lifetime": lifetime,
381
+ "context_error_policy": context_error_policy,
382
+ "close_error_policy": close_error_policy,
383
+ "fallback_to_soft": fallback_to_soft,
384
+ "preserve_lock_file": preserve_lock_file,
385
+ "on_acquired": on_acquired,
386
+ **kwargs,
387
+ }
388
+ if not is_singleton:
389
+ return cls._create_instance(lock_file, params)
390
+
391
+ # Look up, build and store under one lock. Without it two threads racing the first construction for a
392
+ # path both miss the cache and each build their own instance, so callers relying on is_singleton for
393
+ # reentrant locking across instances end up with two "singletons" and acquire()'s deadlock check then
394
+ # rejects a legitimate reentrant acquire; the unguarded writes to the WeakValueDictionary are a data
395
+ # race besides. ReadWriteLock and SoftReadWriteLock already guard their singleton caches this way.
396
+ # Key the cache on the canonical form so equivalent spellings of one path share a singleton, and it matches the
397
+ # deadlock-registry key acquire() uses.
398
+ singleton_key = _canonical(lock_file)
399
+ with cls._instances_lock:
400
+ if (instance := cls._instances.get(singleton_key)) is None:
401
+ if singleton_key in cls._instances_under_construction: # pragma: needs fork
402
+ msg = f"Singleton lock construction is already active for {lock_file!s}"
403
+ raise RuntimeError(msg)
404
+ construction_registry = cls._instances_under_construction
405
+ construction_pid = os.getpid()
406
+ construction_registry.add(singleton_key)
407
+ try:
408
+ instance = cls._create_instance(lock_file, params)
409
+ finally:
410
+ construction_registry.discard(singleton_key)
411
+ if os.getpid() != construction_pid: # pragma: needs fork
412
+ msg = "Lock construction cannot continue after fork; construct a new lock in the child"
413
+ raise RuntimeError(msg)
414
+ cls._instances[singleton_key] = instance
415
+ return instance
416
+
417
+ params_to_check = {
418
+ "thread_local": (thread_local, instance.is_thread_local()),
419
+ "timeout": (timeout, instance.timeout),
420
+ "mode": (mode, instance._context.mode), # ruff:ignore[private-member-access] # compares against the managed instance's own context
421
+ "blocking": (blocking, instance.blocking),
422
+ "poll_interval": (poll_interval, instance.poll_interval),
423
+ "lifetime": (lifetime, instance.lifetime),
424
+ "context_error_policy": (context_error_policy, instance.context_error_policy),
425
+ "close_error_policy": (close_error_policy, instance.close_error_policy),
426
+ "fallback_to_soft": (fallback_to_soft, instance.fallback_to_soft),
427
+ "preserve_lock_file": (preserve_lock_file, instance.preserve_lock_file),
428
+ }
429
+ non_matching_params = {
430
+ name: (passed_param, set_param)
431
+ for name, (passed_param, set_param) in params_to_check.items()
432
+ if passed_param != set_param
433
+ }
434
+ # Callables compare by identity, not equality: two equal callables can close over different state, so a
435
+ # singleton must reject a different hook object even if it compares equal. Keep it out of the scalar dict above.
436
+ hook_mismatch = on_acquired is not instance.on_acquired
437
+ if not non_matching_params and not hook_mismatch:
438
+ return instance # ty: ignore[invalid-return-type] # https://github.com/astral-sh/ty/issues/3231
439
+
440
+ msg = "Singleton lock instances cannot be initialized with differing arguments"
441
+ msg += "\nNon-matching arguments: "
442
+ for param_name, (passed_param, set_param) in non_matching_params.items():
443
+ msg += f"\n\t{param_name} (existing lock has {set_param} but {passed_param} was passed)"
444
+ if hook_mismatch:
445
+ msg += f"\n\ton_acquired (existing lock has {instance.on_acquired} but {on_acquired} was passed)"
446
+ raise ValueError(msg)
447
+
448
+ def _create_instance(
449
+ cls: type[_T], lock_file: str | os.PathLike[str], params: dict[str, _LockInitValue | _ExtraValue]
450
+ ) -> _T:
451
+ model = _init_parameter_model(cls)
452
+ if model.accepts_kwargs:
453
+ return super().__call__(lock_file, **params)
454
+
455
+ unsupported = sorted(
456
+ name
457
+ for name, value in params.items()
458
+ if name not in model.accepted_params
459
+ and ((parameter := model.default_params.get(name)) is None or value != parameter.default)
460
+ )
461
+ if unsupported:
462
+ msg = f"{cls.__name__} does not support non-default lock options: {', '.join(unsupported)}"
463
+ raise TypeError(msg)
464
+ # virtualenv narrows a BaseFileLock descendant's signature; omit base defaults it does not accept (#340).
465
+ return super().__call__(
466
+ lock_file,
467
+ **{name: value for name, value in params.items() if name in model.accepted_params},
468
+ )
469
+
470
+
471
+ _INIT_PARAMETER_MODELS: Final[WeakKeyDictionary[type[BaseFileLock], _InitParameterModel]] = WeakKeyDictionary()
472
+
473
+
474
+ def _init_parameter_model(cls: type[BaseFileLock]) -> _InitParameterModel:
475
+ # A strong cache would keep dynamically created subclasses alive for the process lifetime.
476
+ with _fork_transition(), _FORK_STATE.parameter_models_lock:
477
+ if (model := _INIT_PARAMETER_MODELS.get(cls)) is None:
478
+ parameters = inspect.signature(cls.__init__).parameters.values()
479
+ model = _InitParameterModel(
480
+ accepted_params=frozenset(
481
+ parameter.name
482
+ for parameter in parameters
483
+ if parameter.kind in {inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY}
484
+ ),
485
+ accepts_kwargs=any(parameter.kind is inspect.Parameter.VAR_KEYWORD for parameter in parameters),
486
+ default_params={
487
+ name: parameter
488
+ for name, parameter in inspect.signature(type(cls).__call__).parameters.items()
489
+ if parameter.default is not inspect.Parameter.empty
490
+ },
491
+ )
492
+ _INIT_PARAMETER_MODELS[cls] = model
493
+ return model
494
+
495
+
496
+ @dataclass(frozen=True)
497
+ class _InitParameterModel:
498
+ accepted_params: frozenset[str]
499
+ accepts_kwargs: bool
500
+ default_params: dict[str, inspect.Parameter]
501
+
502
+
503
+ def _resolve_lifetime(lifetime: float | None, cls: type[BaseFileLock], *, stacklevel: int) -> float | None:
504
+ """
505
+ Validate ``lifetime`` and drop a value the backend cannot honor.
506
+
507
+ ``lifetime`` is a deliberate age-based lease: a lock file older than ``lifetime`` is broken even while its holder is
508
+ still alive. Existence locks (:class:`SoftFileLock`) implement that behavior by unlinking a reclaimable pathname,
509
+ which can overlap a live holder. A native OS lock lives on the inode, so unlinking the pathname by age cannot revoke
510
+ the kernel lock; a contender would lock a fresh inode and overlap the live holder (#590). Ignore the request with a
511
+ warning rather than accept a setting that breaks mutual exclusion.
512
+ """
513
+ if lifetime is not None:
514
+ if isinstance(lifetime, bool) or not isinstance(lifetime, (int, float)):
515
+ msg = f"lifetime must be a finite non-negative number or None, not {type(lifetime).__name__}"
516
+ raise TypeError(msg)
517
+ if lifetime < 0 or (isinstance(lifetime, float) and not math.isfinite(lifetime)):
518
+ msg = f"lifetime must be finite and non-negative, not {lifetime!r}"
519
+ raise ValueError(msg)
520
+ if lifetime is not None and not cls._lifetime_supported:
521
+ warnings.warn(
522
+ f"lifetime is ignored for {cls.__name__}: {cls._lifetime_unsupported_reason}; "
523
+ f"only SoftFileLock supports lifetime-based expiry",
524
+ stacklevel=stacklevel,
525
+ )
526
+ return None
527
+ if lifetime is not None and cls._lifetime_replacements is not None:
528
+ strict_lock, lease = cls._lifetime_replacements
529
+ warnings.warn(
530
+ f"{cls.__name__}(lifetime=...) uses age-based expiry and can overlap a live holder; "
531
+ f"use {lease} for expiry or {strict_lock} for fail-closed locking",
532
+ SoftFileLockLifetimeWarning,
533
+ stacklevel=stacklevel,
534
+ )
535
+ return lifetime
536
+
537
+
538
+ def _resolve_context_error_policy(policy: str) -> ContextErrorPolicy:
539
+ if policy not in _CONTEXT_ERROR_POLICIES:
540
+ msg = f"context_error_policy must be 'chain' or 'group', got {policy!r}"
541
+ raise ValueError(msg)
542
+ if policy == "group": # fail fast at construction rather than only when a dual failure happens to occur
543
+ try:
544
+ _exception_group_cls()
545
+ except ImportError as exc: # pragma: no cover # only on 3.10 without the exceptiongroup backport
546
+ msg = "context_error_policy='group' requires Python 3.11+ or the 'exceptiongroup' backport installed"
547
+ raise ValueError(msg) from exc
548
+ return cast("ContextErrorPolicy", policy)
549
+
550
+
551
+ def _resolve_close_error_policy(policy: str) -> CloseErrorPolicy:
552
+ if policy not in _CLOSE_ERROR_POLICIES:
553
+ msg = f"close_error_policy must be 'default', 'raise', or 'suppress', got {policy!r}"
554
+ raise ValueError(msg)
555
+ return cast("CloseErrorPolicy", policy)
556
+
557
+
558
+ def _resolve_preserve_lock_file(*, preserve: bool, supported: bool, cls_name: str) -> bool:
559
+ # An existence lock unlinks its marker to release, so preserving the pathname would defeat unlocking. Reject the
560
+ # request rather than silently ignore it, since a caller asking for a stable identity must know it cannot be kept.
561
+ if preserve and not supported:
562
+ msg = f"preserve_lock_file=True is not supported by {cls_name}: unlinking its marker is how it releases"
563
+ raise ValueError(msg)
564
+ return preserve
565
+
566
+
567
+ def _resolve_on_acquired(
568
+ on_acquired: Callable[[int], None] | None, *, supported: bool, cls_name: str
569
+ ) -> Callable[[int], None] | None:
570
+ if on_acquired is None:
571
+ return None
572
+ # An existence lock stores protocol state in its marker, so a caller writing through the descriptor would corrupt
573
+ # stale detection and ownership metadata; only native locks lend out the descriptor.
574
+ if not supported:
575
+ msg = f"on_acquired is not supported by {cls_name}: only native locks expose the lock descriptor"
576
+ raise ValueError(msg)
577
+ # A hook that fails and then also fails to release surfaces both errors as a BaseExceptionGroup. Require that class
578
+ # at construction rather than at the rare moment both fail, matching how context_error_policy='group' validates.
579
+ try:
580
+ _exception_group_cls()
581
+ except ImportError as exc: # pragma: no cover # only on 3.10 without the exceptiongroup backport
582
+ msg = "on_acquired requires Python 3.11+ or the 'exceptiongroup' backport for its rollback error path"
583
+ raise ValueError(msg) from exc
584
+ return on_acquired
585
+
586
+
587
+ class BaseFileLock(contextlib.ContextDecorator, metaclass=FileLockMeta): # ruff:ignore[too-many-public-methods] # public config properties
588
+ """
589
+ Abstract base class for a file lock object.
590
+
591
+ Provides the common reentrant API and state management. Subclasses implement the locking mechanism
592
+ (:class:`UnixFileLock <filelock.UnixFileLock>`, :class:`WindowsFileLock <filelock.WindowsFileLock>`,
593
+ :class:`SoftFileLock <filelock.SoftFileLock>`).
594
+
595
+ """
596
+
597
+ _instances: WeakValueDictionary[str, BaseFileLock]
598
+ _instances_lock: RLock
599
+ _instances_under_construction: set[str]
600
+
601
+ #: How the cross-instance deadlock message names the conflicting holder; the async subclass says "task".
602
+ _deadlock_holder_desc: str = "FileLock instance in this thread"
603
+
604
+ #: Whether an age-based :attr:`lifetime` lease may break this lock. Only existence locks set it (they reclaim by
605
+ #: unlinking a pathname); native OS locks leave it ``False`` since a kernel lock cannot be revoked by file age.
606
+ _lifetime_supported: bool = False
607
+
608
+ #: Strict-lock and lease replacements for a backend with legacy age-based expiry.
609
+ _lifetime_replacements: tuple[str, str] | None = None
610
+
611
+ #: Why a backend that refuses ``lifetime`` cannot honor it, named in the warning that drops the value.
612
+ _lifetime_unsupported_reason: str = "a native OS lock cannot be broken safely by file age"
613
+
614
+ #: Async construction adds one metaclass frame before lifetime validation.
615
+ _constructor_lifetime_warning_stacklevel: int = 3
616
+
617
+ #: Whether :attr:`preserve_lock_file` may be ``True``. Native locks keep the pathname on release, so they support
618
+ #: it; existence locks unlink their marker to release and reject it.
619
+ _preserve_lock_file_supported: bool = True
620
+
621
+ #: Whether an :attr:`on_acquired` hook may be set. Native locks lend the descriptor out; existence locks keep
622
+ #: protocol state in the marker and reject it.
623
+ _on_acquired_supported: bool = True
624
+
625
+ #: Whether a shared instance serializes its physical acquire and release behind one gate. A backend that publishes
626
+ #: several files per owner needs it; a single-file backend is atomic and leaves it off to skip the gate entirely.
627
+ _serialize_transitions: bool = False
628
+
629
+ #: Ceiling in seconds on the jittered backoff between contended acquisition retries. ``0`` keeps the fixed
630
+ #: poll cadence; a multi-file backend sets it so contending processes desynchronize instead of livelocking.
631
+ _poll_backoff_cap: float = 0.0
632
+
633
+ def __init_subclass__(cls, **kwargs: _SubclassValue) -> None:
634
+ """Give each lock subclass its own singleton registry and lock."""
635
+ super().__init_subclass__(**kwargs)
636
+ cls._instances = WeakValueDictionary()
637
+ cls._instances_lock = RLock()
638
+ cls._instances_under_construction = set()
639
+ _register_fork_class(cls)
640
+
641
+ @classmethod
642
+ def _reset_class_after_fork(cls) -> None: # pragma: forked child
643
+ cls._instances = WeakValueDictionary()
644
+ cls._instances_lock = RLock()
645
+ cls._instances_under_construction = set()
646
+
647
+ def __init__( # ruff:ignore[too-many-arguments] # public constructor: one parameter per documented lock option
648
+ self,
649
+ lock_file: str | os.PathLike[str],
650
+ timeout: float = -1,
651
+ mode: int = _UNSET_FILE_MODE,
652
+ thread_local: bool = True, # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility
653
+ *,
654
+ blocking: bool = True,
655
+ is_singleton: bool = False,
656
+ poll_interval: float = 0.05,
657
+ lifetime: float | None = None,
658
+ context_error_policy: ContextErrorPolicy = "chain",
659
+ close_error_policy: CloseErrorPolicy = "default",
660
+ fallback_to_soft: bool = True,
661
+ preserve_lock_file: bool = False,
662
+ on_acquired: Callable[[int], None] | None = None,
663
+ ) -> None:
664
+ """
665
+ Create a new lock object.
666
+
667
+ :param lock_file: path to the file
668
+ :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in the
669
+ acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it to a
670
+ negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock.
671
+ :param mode: file permissions for the lockfile. When not specified, the OS controls permissions via umask and
672
+ default ACLs, preserving POSIX default ACL inheritance in shared directories.
673
+ :param thread_local: Whether this object's internal context should be thread local or not. If this is set to
674
+ ``False`` then the lock will be reentrant across threads. When ``True`` (the default), **all fields of the
675
+ lock's internal context are per-thread**, including the configuration values ``poll_interval``, ``timeout``,
676
+ ``blocking``, ``mode``, and ``lifetime``. Setting one of these properties from one thread does not change
677
+ the value seen by another thread; threads that did not perform the write continue to see the value supplied
678
+ at construction time. If you need configuration values to be visible across threads, construct the lock
679
+ with ``thread_local=False``.
680
+ :param blocking: whether the lock should be blocking or not
681
+ :param is_singleton: If this is set to ``True`` then only one instance of this class will be created per lock
682
+ file. This is useful if you want to use the lock object for reentrant locking without needing to pass the
683
+ same object around.
684
+ :param poll_interval: default interval for polling the lock file, in seconds. It will be used as fallback value
685
+ in the acquire method, if no poll_interval value (``None``) is given.
686
+ :param lifetime: for :class:`SoftFileLock`, the age in seconds after which a waiting process may delete the
687
+ marker, even while its holder remains alive. This legacy expiry mode does not provide strict mutual
688
+ exclusion. ``None`` (the default) disables age-based expiry. Native OS locks (:class:`FileLock`) cannot be
689
+ revoked by file age and ignore a non-``None`` ``lifetime`` with a warning.
690
+ :param context_error_policy: how a context manager reconciles a failure in its body with a failure while
691
+ releasing on exit. ``"chain"`` (the default) keeps Python's behavior: the release error propagates with the
692
+ body error in its ``__context__``. ``"group"`` raises a :class:`BaseExceptionGroup` holding the body error
693
+ first and the release error second, so neither hides the other.
694
+ :param close_error_policy: what to do with an ``os.close`` failure after relinquishing descriptor ownership.
695
+ ``"default"`` keeps each backend's historical behavior (Unix native locks drop a FUSE/Docker ``EIO``;
696
+ Windows native locks and :class:`SoftFileLock` propagate); ``"raise"`` always propagates the ``OSError``;
697
+ ``"suppress"`` always ignores it. Held state is released either way. It does not affect unlock failures or
698
+ lock-file deletion.
699
+ :param fallback_to_soft: for :class:`UnixFileLock`, whether to switch to :class:`SoftFileLock` when the
700
+ filesystem's ``flock`` returns ``ENOSYS``. ``True`` (the default) keeps the historical fallback;
701
+ ``False`` fails closed, letting the ``ENOSYS`` propagate so a caller that needs kernel-enforced
702
+ locking is never silently downgraded. It has no effect on Windows or :class:`SoftFileLock`.
703
+ :param preserve_lock_file: for native locks (:class:`FileLock`), whether filelock promises not to unlink the
704
+ lock pathname on release. ``False`` (the default) keeps each backend's cleanup: Windows removes the lock
705
+ file, Unix already leaves it. ``True`` keeps a stable file identity for ACLs, auditing, and holder metadata:
706
+ Windows skips its post-release unlink and Unix refuses to enter the ``ENOSYS`` soft fallback (which releases
707
+ by unlinking). :class:`SoftFileLock` rejects ``True``. The promise covers filelock's own release path only;
708
+ it cannot stop another process or the filesystem from removing the pathname.
709
+ :param on_acquired: for native locks (:class:`FileLock`), a callable invoked with the borrowed lock descriptor
710
+ once per physical acquisition, after filelock holds the native lock and finished backend initialization but
711
+ before :meth:`~BaseFileLock.acquire` returns. Recursive acquisitions do not call it again. The callback may
712
+ read, write, seek, truncate, or set metadata through ``os`` on the descriptor, but must not close, unlock,
713
+ or take ownership of it, and filelock does not fsync its writes. If it raises, filelock releases the lock
714
+ and re-raises. :class:`SoftFileLock` rejects the hook.
715
+
716
+ """
717
+ self._creator_pid = os.getpid()
718
+ self._transition_lock = RLock()
719
+ self._is_thread_local = thread_local
720
+ self._is_singleton = is_singleton
721
+ self._context_error_policy = context_error_policy # already validated by the metaclass
722
+ self._close_error_policy = close_error_policy # already validated by the metaclass
723
+ self._fallback_to_soft = fallback_to_soft
724
+ self._preserve_lock_file = preserve_lock_file # already validated by the metaclass
725
+ self._on_acquired = on_acquired # already validated by the metaclass
726
+
727
+ self._context: FileLockContext = (ThreadLocalFileContext if thread_local else FileLockContext)(
728
+ lock_file=os.fspath(lock_file),
729
+ timeout=timeout,
730
+ mode=mode,
731
+ blocking=blocking,
732
+ poll_interval=poll_interval,
733
+ lifetime=lifetime,
734
+ )
735
+ _register_fork_object(self)
736
+
737
+ def is_thread_local(self) -> bool:
738
+ """:returns: a flag indicating if this lock is thread local or not"""
739
+ return self._is_thread_local
740
+
741
+ @property
742
+ def is_singleton(self) -> bool:
743
+ """
744
+ A flag indicating if this lock is singleton or not.
745
+
746
+ .. versionadded:: 3.13.0
747
+
748
+ """
749
+ return self._is_singleton
750
+
751
+ @property
752
+ def context_error_policy(self) -> ContextErrorPolicy:
753
+ """
754
+ How a context manager reconciles a body failure with a release failure on exit.
755
+
756
+ .. versionadded:: 3.30.0
757
+
758
+ """
759
+ return self._context_error_policy
760
+
761
+ @property
762
+ def close_error_policy(self) -> CloseErrorPolicy:
763
+ """
764
+ What a lock does with an ``os.close`` failure after relinquishing descriptor ownership.
765
+
766
+ .. versionadded:: 3.30.0
767
+
768
+ """
769
+ return self._close_error_policy
770
+
771
+ def _close_released_fd(self, fd: int, *, default_suppresses: bool) -> None:
772
+ # CPython never retries close() after EINTR because the descriptor number may already be reused, so neither does
773
+ # this. close_error_policy decides the error's fate after the backend relinquishes descriptor ownership.
774
+ try:
775
+ os.close(fd)
776
+ except OSError:
777
+ if self._close_error_policy == "suppress" or (self._close_error_policy == "default" and default_suppresses):
778
+ return
779
+ raise
780
+
781
+ @property
782
+ def fallback_to_soft(self) -> bool:
783
+ """
784
+ Whether a :class:`FileLock` falls back to :class:`SoftFileLock` when the filesystem lacks ``flock``.
785
+
786
+ Only :class:`UnixFileLock` acts on it: when ``False`` an ``ENOSYS`` from ``flock`` propagates instead of
787
+ switching to existence-lock semantics.
788
+
789
+ .. versionadded:: 3.30.0
790
+
791
+ """
792
+ return self._fallback_to_soft
793
+
794
+ @property
795
+ def preserve_lock_file(self) -> bool:
796
+ """
797
+ Whether filelock promises not to unlink the lock pathname on release.
798
+
799
+ When ``True``, Windows skips its post-release unlink and Unix refuses the ``ENOSYS`` soft fallback.
800
+ :class:`SoftFileLock` rejects ``True`` because unlinking its marker is how it releases.
801
+
802
+ .. versionadded:: 3.30.0
803
+
804
+ """
805
+ return self._preserve_lock_file
806
+
807
+ @property
808
+ def on_acquired(self) -> Callable[[int], None] | None:
809
+ """
810
+ The callback run with the borrowed lock descriptor once per physical acquisition, or ``None``.
811
+
812
+ Native locks only. It runs after the native lock is held and backend initialization finished, before
813
+ :meth:`~BaseFileLock.acquire` returns; a raise rolls back the acquisition. :class:`SoftFileLock` rejects it.
814
+
815
+ .. versionadded:: 3.30.0
816
+
817
+ """
818
+ return self._on_acquired
819
+
820
+ @property
821
+ def lock_file(self) -> str:
822
+ """Path to the lock file."""
823
+ return self._context.lock_file
824
+
825
+ @property
826
+ def timeout(self) -> float:
827
+ """
828
+ The default timeout value, in seconds.
829
+
830
+ .. versionadded:: 2.0.0
831
+
832
+ """
833
+ return self._context.timeout
834
+
835
+ @timeout.setter
836
+ def timeout(self, value: float | str) -> None:
837
+ """
838
+ Change the default timeout value.
839
+
840
+ :param value: the new value, in seconds
841
+
842
+ """
843
+ self._context.timeout = float(value)
844
+
845
+ @property
846
+ def blocking(self) -> bool:
847
+ """
848
+ Whether the locking is blocking or not.
849
+
850
+ .. versionadded:: 3.14.0
851
+
852
+ """
853
+ return self._context.blocking
854
+
855
+ @blocking.setter
856
+ def blocking(self, value: bool) -> None:
857
+ """
858
+ Change the default blocking value.
859
+
860
+ :param value: the new value as bool
861
+
862
+ """
863
+ self._context.blocking = value
864
+
865
+ @property
866
+ def poll_interval(self) -> float:
867
+ """
868
+ The default polling interval, in seconds.
869
+
870
+ .. versionadded:: 3.24.0
871
+
872
+ """
873
+ return self._context.poll_interval
874
+
875
+ @poll_interval.setter
876
+ def poll_interval(self, value: float) -> None:
877
+ """
878
+ Change the default polling interval.
879
+
880
+ :param value: the new value, in seconds
881
+
882
+ """
883
+ self._context.poll_interval = value
884
+
885
+ @property
886
+ def lifetime(self) -> float | None:
887
+ """
888
+ The soft marker age in seconds that permits expiry, or ``None`` to disable age-based expiry.
889
+
890
+ A non-``None`` value permits a waiter to enter while the previous holder remains active, so it does not provide
891
+ strict mutual exclusion. Native locks ignore the value with a warning.
892
+
893
+ .. versionadded:: 3.24.0
894
+
895
+ """
896
+ return self._context.lifetime
897
+
898
+ @lifetime.setter
899
+ def lifetime(self, value: float | None) -> None:
900
+ """
901
+ Change the legacy age-based expiry threshold.
902
+
903
+ :param value: the new value in seconds, or ``None`` to disable expiration
904
+
905
+ :raises ValueError: if *value* is negative or not finite
906
+ :raises TypeError: if *value* is not ``None`` and not a real number
907
+
908
+ """
909
+ self._context.lifetime = _resolve_lifetime(value, type(self), stacklevel=3)
910
+
911
+ @property
912
+ def mode(self) -> int:
913
+ """The file permissions for the lockfile."""
914
+ return 0o644 if self._context.mode == _UNSET_FILE_MODE else self._context.mode
915
+
916
+ @property
917
+ def has_explicit_mode(self) -> bool:
918
+ """Whether the file permissions were explicitly set."""
919
+ return self._context.mode != _UNSET_FILE_MODE
920
+
921
+ def _open_mode(self) -> int:
922
+ """Mode for ``os.open``: 0o666 when unset so umask and ACLs decide, otherwise the explicit mode."""
923
+ return 0o666 if self._context.mode == _UNSET_FILE_MODE else self._context.mode
924
+
925
+ @property
926
+ def is_locked(self) -> bool:
927
+ """
928
+ A boolean indicating if the lock file is holding the lock currently.
929
+
930
+ .. versionchanged:: 2.0.0
931
+
932
+ This was previously a method and is now a property.
933
+
934
+ """
935
+ _ensure_current_process()
936
+ return self._context.lock_file_fd is not None
937
+
938
+ @property
939
+ def lock_counter(self) -> int:
940
+ """The number of times this lock has been acquired (but not yet released)."""
941
+ _ensure_current_process()
942
+ return self._context.lock_counter
943
+
944
+ def __enter__(self) -> Self:
945
+ """
946
+ Acquire the lock.
947
+
948
+ :returns: the lock object
949
+
950
+ """
951
+ self.acquire()
952
+ return self
953
+
954
+ def __exit__(
955
+ self,
956
+ exc_type: type[BaseException] | None,
957
+ exc_value: BaseException | None,
958
+ traceback: TracebackType | None,
959
+ ) -> None:
960
+ """Release the lock, reconciling a release failure with any body failure per :attr:`context_error_policy`."""
961
+ self._release_in_context(exc_value)
962
+
963
+ def _release_in_context(self, body_error: BaseException | None) -> None:
964
+ # Release from a context-manager exit. "chain" lets a release failure propagate with the body error already in
965
+ # its __context__ (Python's default); "group" raises both as sibling leaves so neither one hides the other.
966
+ try:
967
+ self.release()
968
+ except BaseException as release_error:
969
+ if body_error is None or self._context_error_policy == "chain":
970
+ raise
971
+ _raise_body_and_release(body_error, release_error)
972
+
973
+ def __del__(self) -> None:
974
+ """Force-release so a dropped reference never leaks a held lock."""
975
+ if vars(self).get("_creator_pid") != os.getpid():
976
+ return # pragma: forked child
977
+ # A finalizer must not raise. A release error during garbage collection would otherwise surface as an
978
+ # unraisable-exception warning, attributed to whichever code triggered collection. The dropped lock still gets
979
+ # best-effort cleanup; an explicit release() reports the same error to a caller who can act on it.
980
+ with contextlib.suppress(Exception):
981
+ self.release(force=True)
982
+
983
+ def acquire(
984
+ self,
985
+ timeout: float | None = None,
986
+ poll_interval: float | None = None,
987
+ *,
988
+ poll_intervall: float | None = None,
989
+ blocking: bool | None = None,
990
+ cancel_check: Callable[[], bool] | None = None,
991
+ ) -> AcquireReturnProxy:
992
+ """
993
+ Try to acquire the file lock.
994
+
995
+ :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default :attr:`~timeout` is and
996
+ if ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired
997
+ :param poll_interval: interval of trying to acquire the lock file, ``None`` means use the default
998
+ :attr:`~poll_interval`
999
+ :param poll_intervall: deprecated, kept for backwards compatibility, use ``poll_interval`` instead
1000
+ :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the
1001
+ first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.
1002
+ :param cancel_check: a callable returning ``True`` when the acquisition should be canceled. Checked on each poll
1003
+ iteration. When triggered, raises :class:`~Timeout` just like an expired timeout.
1004
+
1005
+ :returns: a context object that will unlock the file when the context is exited
1006
+
1007
+ :raises Timeout: if fails to acquire lock within the timeout period
1008
+
1009
+ .. code-block:: python
1010
+
1011
+ # You can use this method in the context manager (recommended)
1012
+ with lock.acquire():
1013
+ pass
1014
+
1015
+ # Or use an equivalent try-finally construct:
1016
+ lock.acquire()
1017
+ try:
1018
+ pass
1019
+ finally:
1020
+ lock.release()
1021
+
1022
+ .. versionchanged:: 2.0.0
1023
+
1024
+ This method returns now a *proxy* object instead of *self*, so that it can be used in a with statement
1025
+ without side effects.
1026
+
1027
+ """
1028
+ self._raise_if_inherited()
1029
+ if timeout is None:
1030
+ timeout = self._context.timeout
1031
+
1032
+ if blocking is None:
1033
+ blocking = self._context.blocking
1034
+
1035
+ if poll_intervall is not None:
1036
+ msg = "use poll_interval instead of poll_intervall"
1037
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
1038
+ poll_interval = poll_intervall
1039
+
1040
+ poll_interval = poll_interval if poll_interval is not None else self._context.poll_interval
1041
+
1042
+ start_time = time.perf_counter()
1043
+ # Wait for admission before touching any state: a caller refused entry must leave the counter, the registry and
1044
+ # the descriptor exactly as it found them.
1045
+ with self._transition_admission(
1046
+ blocking=blocking,
1047
+ cancel_check=cancel_check,
1048
+ timeout=timeout,
1049
+ poll_interval=poll_interval,
1050
+ start_time=start_time,
1051
+ ):
1052
+ # Bump the counter up front; _undo_acquire rolls it back if acquisition fails.
1053
+ self._context.lock_counter += 1
1054
+
1055
+ canonical = _canonical(self.lock_file)
1056
+ self._raise_if_would_deadlock(canonical, timeout=timeout, blocking=blocking)
1057
+
1058
+ try:
1059
+ self._poll_until_acquired(
1060
+ blocking=blocking,
1061
+ cancel_check=cancel_check,
1062
+ timeout=timeout,
1063
+ poll_interval=poll_interval,
1064
+ start_time=start_time,
1065
+ )
1066
+ except BaseException:
1067
+ self._reconcile_failed_acquire(canonical)
1068
+ raise
1069
+ self._commit_acquire(canonical)
1070
+ return AcquireReturnProxy(lock=self)
1071
+
1072
+ @contextlib.contextmanager
1073
+ def _transition_admission(
1074
+ self,
1075
+ *,
1076
+ blocking: bool,
1077
+ cancel_check: Callable[[], bool] | None,
1078
+ timeout: float,
1079
+ poll_interval: float,
1080
+ start_time: float,
1081
+ ) -> Generator[None]:
1082
+ # One thread at a time drives the physical transition of a shared instance. A protocol that publishes several
1083
+ # files per owner leaves a half-built claim visible otherwise, and a second thread would read it as a holder.
1084
+ # Only such a backend opts in; a single-file backend and a thread-local context each need no gate.
1085
+ if not self._serialize_transitions or self._is_thread_local:
1086
+ yield
1087
+ return
1088
+ while not self._transition_lock.acquire(blocking=False): # pragma: needs hard-link
1089
+ if not blocking or (cancel_check is not None and cancel_check()):
1090
+ raise Timeout(self.lock_file)
1091
+ if timeout >= 0 and time.perf_counter() - start_time >= timeout:
1092
+ raise Timeout(self.lock_file)
1093
+ time.sleep(poll_interval)
1094
+ try: # pragma: needs hard-link
1095
+ yield
1096
+ finally: # pragma: needs hard-link
1097
+ self._transition_lock.release()
1098
+
1099
+ def release(self, force: bool = False) -> None: # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility
1100
+ """
1101
+ Release the file lock. The lock is only completely released when the lock counter reaches 0. The lock file
1102
+ itself may be deleted automatically, the behavior is platform-specific.
1103
+
1104
+ :param force: If true, the lock counter is ignored and the lock is released in every case.
1105
+
1106
+ """
1107
+ # A shared instance releases under the same gate its acquisition ran through, so a thread entering the lock
1108
+ # never observes a partially torn-down owner.
1109
+ serialize = self._serialize_transitions and not self._is_thread_local
1110
+ with self._transition_lock if serialize else contextlib.nullcontext():
1111
+ if self._creator_pid != os.getpid() or not self.is_locked:
1112
+ return
1113
+ if not force and self._context.lock_counter > 1:
1114
+ self._context.lock_counter -= 1
1115
+ return
1116
+
1117
+ lock_id, lock_filename = id(self), self.lock_file
1118
+ _LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename)
1119
+ try:
1120
+ self._release_with_fork_tracking()
1121
+ except BaseException:
1122
+ # A failure after the OS unlock (during close or unlink) still released the lock: the backend cleared
1123
+ # its descriptor, so commit the counter and registry to released even as the cleanup error propagates.
1124
+ # A failure that left the lock held keeps the counter so a later release can retry the OS unlock.
1125
+ if not self.is_locked:
1126
+ self._commit_release()
1127
+ raise
1128
+ self._commit_release()
1129
+ _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename)
1130
+
1131
+ def _raise_if_inherited(self) -> None:
1132
+ if self._creator_pid != os.getpid(): # pragma: forked child
1133
+ msg = f"{type(self).__name__} on {self.lock_file} was inherited across fork; construct a new instance"
1134
+ raise RuntimeError(msg)
1135
+
1136
+ def _mark_descriptor_owned(self, fd: int, identity: tuple[int, int] | None = None) -> None:
1137
+ self._context.pending_lock_file_fd = None
1138
+ self._context.pending_lock_file_fd_identity = None
1139
+ self._context.lock_file_fd = fd
1140
+ self._context.lock_file_fd_identity = identity
1141
+
1142
+ def _mark_descriptor_pending(self, fd: int, identity: tuple[int, int] | None = None) -> None:
1143
+ self._context.pending_lock_file_fd = fd
1144
+ self._context.pending_lock_file_fd_identity = identity
1145
+
1146
+ def _mark_descriptor_released(self) -> None:
1147
+ self._context.pending_lock_file_fd = None
1148
+ self._context.pending_lock_file_fd_identity = None
1149
+ self._context.lock_file_fd = None
1150
+ self._context.lock_file_fd_identity = None
1151
+
1152
+ def _reset_after_fork_in_child(self) -> None: # pragma: forked child
1153
+ # fork copies the lock in whatever state the parent's threads left it, so give the child an unheld one.
1154
+ self._transition_lock = RLock()
1155
+ self._context.owner_claim_paths = ()
1156
+ self._context.claim_root = None
1157
+ self._context.lock_file_fd = None
1158
+ self._context.lock_file_fd_token = None
1159
+ self._context.lock_file_fd_identity = None
1160
+ self._context.pending_lock_file_fd = None
1161
+ self._context.pending_lock_file_fd_identity = None
1162
+ self._context.lock_counter = 0
1163
+ self._context.lock_file_key = None
1164
+
1165
+ def _descriptors_for_fork(self) -> tuple[tuple[int, tuple[int, int] | None], ...]: # pragma: needs fork
1166
+ descriptors: list[tuple[int, tuple[int, int] | None]] = []
1167
+ if self._context.lock_file_fd is not None and self._context.lock_file_fd_token is None:
1168
+ descriptors.append((self._context.lock_file_fd, self._context.lock_file_fd_identity))
1169
+ if self._context.pending_lock_file_fd is not None:
1170
+ descriptors.append((self._context.pending_lock_file_fd, self._context.pending_lock_file_fd_identity))
1171
+ return tuple(descriptors)
1172
+
1173
+ def _raise_if_would_deadlock(self, canonical: str, *, timeout: float, blocking: bool) -> None:
1174
+ """
1175
+ Fail fast when a *different* live instance already holds this path in the current deadlock scope.
1176
+
1177
+ Only the first, indefinitely-blocking acquire can self-deadlock this way: waiting in the OS primitive would
1178
+ block on a lock this flow already owns. A finite timeout or ``blocking=False`` keeps the normal Timeout path.
1179
+ """
1180
+ would_block = self._context.lock_counter == 1 and not self.is_locked and timeout < 0 and blocking
1181
+ if would_block and _registry.held.get(self._registry_key(canonical)) not in {None, id(self)}:
1182
+ self._context.lock_counter -= 1
1183
+ msg = (
1184
+ f"Deadlock: lock '{self.lock_file}' is already held by a different {self._deadlock_holder_desc}. "
1185
+ f"Use is_singleton=True to enable reentrant locking across instances."
1186
+ )
1187
+ raise RuntimeError(msg)
1188
+
1189
+ def _registry_key(self, canonical: str) -> Hashable:
1190
+ return canonical if (scope := self._deadlock_scope()) is None else (scope, canonical)
1191
+
1192
+ @staticmethod
1193
+ def _deadlock_scope() -> Hashable | None:
1194
+ """
1195
+ Execution unit whose own hold would deadlock a new acquire.
1196
+
1197
+ ``None`` scopes holders to the thread, which the thread-local registry already separates. Async locks
1198
+ override it with the running task, since one event loop thread runs many tasks and only a reacquire from
1199
+ the *same* task can self-deadlock.
1200
+ """
1201
+ return None
1202
+
1203
+ def _poll_until_acquired(
1204
+ self,
1205
+ *,
1206
+ blocking: bool,
1207
+ cancel_check: Callable[[], bool] | None,
1208
+ timeout: float,
1209
+ poll_interval: float,
1210
+ start_time: float,
1211
+ ) -> None:
1212
+ lock_id = id(self)
1213
+ lock_filename = self.lock_file
1214
+ attempt = 0
1215
+ while True:
1216
+ self._raise_if_inherited()
1217
+ if not self.is_locked:
1218
+ self._try_break_expired_lock()
1219
+ _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename)
1220
+ self._acquire_with_fork_tracking()
1221
+ self._raise_if_inherited()
1222
+ if self.is_locked:
1223
+ _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename)
1224
+ return
1225
+ if self._check_give_up(
1226
+ blocking=blocking,
1227
+ cancel_check=cancel_check,
1228
+ timeout=timeout,
1229
+ start_time=start_time,
1230
+ ):
1231
+ raise Timeout(lock_filename)
1232
+ attempt += 1
1233
+ delay = self._poll_delay(poll_interval, attempt)
1234
+ msg = "Lock %s not acquired on %s, waiting %s seconds ..."
1235
+ _LOGGER.debug(msg, lock_id, lock_filename, delay)
1236
+ time.sleep(delay)
1237
+
1238
+ def _poll_delay(self, poll_interval: float, attempt: int) -> float:
1239
+ # A single-file lock retries on a fixed cadence. A backend that publishes several files per acquisition sets a
1240
+ # cap, and then contending processes back off across a jittered, exponentially widening window instead of
1241
+ # colliding on every poll; poll_interval stays the floor so a lone waiter is still responsive.
1242
+ if not self._poll_backoff_cap:
1243
+ return poll_interval
1244
+ # Cap the exponent before doubling: under heavy contention attempt reaches the thousands, and 2**attempt would
1245
+ # overflow the float multiply long before the window itself stops growing past the cap.
1246
+ window = min(
1247
+ self._poll_backoff_cap, poll_interval * 2 ** min(attempt, _MAX_BACKOFF_EXPONENT)
1248
+ ) # pragma: needs hard-link
1249
+ return max(poll_interval, secrets.randbelow(int(window * 1_000_000) + 1) / 1_000_000) # pragma: needs hard-link
1250
+
1251
+ def _reconcile_failed_acquire(self, canonical: str) -> None:
1252
+ # An acquire that raised while still holding the native lock (a hook that failed and whose rollback could not
1253
+ # release) must keep the registry entry so a later release can retry the OS unlock; otherwise roll the counter
1254
+ # back. is_locked was already reconciled by whichever release ran.
1255
+ if self.is_locked:
1256
+ self._commit_acquire(canonical)
1257
+ else:
1258
+ self._undo_acquire()
1259
+
1260
+ def _invoke_on_acquired(self) -> None:
1261
+ # The wrapper runs in the backend executor for async locks, preserving the callback's documented thread.
1262
+ if self._on_acquired is None or self._context.lock_counter != 1:
1263
+ return
1264
+ try:
1265
+ self._on_acquired(cast("int", self._context.lock_file_fd))
1266
+ except BaseException as callback_error: # arbitrary caller code; roll back on any failure
1267
+ callback_context = callback_error.__context__
1268
+ try:
1269
+ self._release_with_fork_tracking()
1270
+ except BaseException as release_error: # ruff:ignore[blind-except] # both errors surface via the group below
1271
+ _raise_body_and_release(callback_error, release_error)
1272
+ callback_error.__context__ = callback_context
1273
+ raise
1274
+
1275
+ def _acquire_with_fork_tracking(self) -> None:
1276
+ with _fork_transition(self):
1277
+ try:
1278
+ self._acquire()
1279
+ except BaseException as acquisition_error:
1280
+ self._rollback_failed_acquire(acquisition_error)
1281
+ raise
1282
+ try:
1283
+ self._register_context_descriptor()
1284
+ except BaseException as registration_error: # pragma: needs fork
1285
+ self._rollback_failed_registration(registration_error)
1286
+ raise
1287
+ if self.is_locked:
1288
+ self._invoke_on_acquired()
1289
+
1290
+ def _rollback_failed_acquire(self, acquisition_error: BaseException) -> None:
1291
+ if not self.is_locked:
1292
+ return
1293
+ registration_error: BaseException | None = None
1294
+ tracking_error: BaseException | None = None
1295
+ try:
1296
+ self._register_context_descriptor()
1297
+ except BaseException as error: # ruff:ignore[blind-except] # preserve registration and acquisition failures
1298
+ registration_error = error
1299
+ try:
1300
+ # Rollback may fail too; retain the fd so a child can close it without another identity probe.
1301
+ self._register_unverified_context_descriptor()
1302
+ except BaseException as error: # ruff:ignore[blind-except] # pragma: no cover - allocation/control-flow during fallback
1303
+ tracking_error = error
1304
+ try:
1305
+ self._release_with_fork_tracking()
1306
+ except BaseException as rollback_error: # ruff:ignore[blind-except] # preserve rollback and acquisition failures
1307
+ _raise_cleanup_errors(
1308
+ "lock acquisition cleanup failed",
1309
+ acquisition_error,
1310
+ registration_error,
1311
+ tracking_error,
1312
+ rollback_error,
1313
+ )
1314
+ if registration_error is not None: # pragma: needs fork
1315
+ _raise_cleanup_errors(
1316
+ "lock acquisition cleanup failed", acquisition_error, registration_error, tracking_error
1317
+ )
1318
+
1319
+ def _rollback_failed_registration(self, registration_error: BaseException) -> None: # pragma: needs fork
1320
+ tracking_error: BaseException | None = None
1321
+ try:
1322
+ # Rollback may fail too; retain the fd so a child can close it without another identity probe.
1323
+ self._register_unverified_context_descriptor()
1324
+ except BaseException as error: # ruff:ignore[blind-except] # pragma: no cover - allocation/control-flow during fallback
1325
+ tracking_error = error
1326
+ try:
1327
+ self._release_with_fork_tracking()
1328
+ except BaseException as rollback_error: # ruff:ignore[blind-except] # preserve rollback and registration failures
1329
+ _raise_cleanup_errors(
1330
+ "descriptor registration cleanup failed", registration_error, tracking_error, rollback_error
1331
+ )
1332
+ if tracking_error is not None: # pragma: no cover - requires failed in-memory fallback
1333
+ _raise_cleanup_errors("descriptor registration cleanup failed", registration_error, tracking_error)
1334
+
1335
+ def _release_with_fork_tracking(self) -> None:
1336
+ with _fork_transition(self):
1337
+ try:
1338
+ self._release()
1339
+ finally:
1340
+ self._unregister_released_descriptor()
1341
+
1342
+ def _register_context_descriptor(self) -> None:
1343
+ if self._context.lock_file_fd is not None and self._context.lock_file_fd_token is None:
1344
+ self._context.lock_file_fd_token = _register_owned_descriptor(
1345
+ self._context.lock_file_fd,
1346
+ self._context.lock_file_fd_identity,
1347
+ )
1348
+
1349
+ def _register_unverified_context_descriptor(self) -> None:
1350
+ # The rollback only reaches here still holding a descriptor it never managed to register.
1351
+ if self._context.lock_file_fd is not None and self._context.lock_file_fd_token is None: # pragma: no branch
1352
+ self._context.lock_file_fd_token = _register_unverified_owned_descriptor(self._context.lock_file_fd)
1353
+
1354
+ def _unregister_released_descriptor(self) -> None:
1355
+ if self._context.lock_file_fd is None:
1356
+ if (token := self._context.lock_file_fd_token) is not None: # pragma: needs fork
1357
+ _unregister_owned_descriptor(token)
1358
+ self._context.lock_file_fd_token = None
1359
+ self._context.lock_file_fd_identity = None
1360
+
1361
+ def _undo_acquire(self) -> None:
1362
+ """Roll back the counter after a failed acquire, dropping the registry entry once nothing holds the path."""
1363
+ self._context.lock_counter = max(0, self._context.lock_counter - 1)
1364
+ if self._context.lock_counter == 0:
1365
+ self._drop_registry_entry()
1366
+
1367
+ def _commit_acquire(self, canonical: str) -> None:
1368
+ """Record this instance as the holder once the first acquire succeeds, so peers can detect the deadlock."""
1369
+ if self._context.lock_counter == 1:
1370
+ key = self._registry_key(canonical)
1371
+ # The holder scope is resolved once at commit so a later release from another flow drops the right entry.
1372
+ self._context.lock_file_key = key
1373
+ _registry.held[key] = id(self)
1374
+
1375
+ def _drop_registry_entry(self) -> None:
1376
+ """Forget the key owned by this hold without resolving a mutable path again."""
1377
+ key = self._context.lock_file_key
1378
+ self._context.lock_file_key = None
1379
+ if key is not None:
1380
+ _registry.held.pop(key, None)
1381
+
1382
+ def _commit_release(self) -> None:
1383
+ """Record the lock as fully released: reset the recursion counter and drop the deadlock-registry entry."""
1384
+ self._context.lock_counter = 0
1385
+ self._drop_registry_entry()
1386
+
1387
+ def _try_break_expired_lock(self) -> None:
1388
+ """Remove the lock file if its modification time exceeds the configured :attr:`lifetime`."""
1389
+ if (lifetime := self._context.lifetime) is None:
1390
+ return
1391
+ with contextlib.suppress(OSError):
1392
+ # lstat, not stat: an attacker with write access to the lock directory can replace a held
1393
+ # lock file with a symlink pointing at an old file, making stat() report the target's stale
1394
+ # mtime so a waiter breaks a live lock and two processes hold it at once. lstat reads the
1395
+ # symlink's own mtime, matching the O_NOFOLLOW reads elsewhere.
1396
+ st = os.lstat(self.lock_file)
1397
+ if time.time() - st.st_mtime < lifetime:
1398
+ return
1399
+ break_lock_file(self.lock_file, st.st_mtime, st.st_ino)
1400
+
1401
+ def _check_give_up(
1402
+ self,
1403
+ *,
1404
+ blocking: bool,
1405
+ cancel_check: Callable[[], bool] | None,
1406
+ timeout: float,
1407
+ start_time: float,
1408
+ ) -> bool:
1409
+ lock_id, lock_filename = id(self), self.lock_file
1410
+ if blocking is False:
1411
+ _LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename)
1412
+ return True
1413
+ if cancel_check is not None and cancel_check():
1414
+ _LOGGER.debug("Cancellation requested for lock %s on %s", lock_id, lock_filename)
1415
+ return True
1416
+ if 0 <= timeout < time.perf_counter() - start_time:
1417
+ _LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename)
1418
+ return True
1419
+ return False
1420
+
1421
+ @abstractmethod
1422
+ def _acquire(self) -> None:
1423
+ """If the file lock could be acquired, self._context.lock_file_fd holds the file descriptor of the lock file."""
1424
+ raise NotImplementedError
1425
+
1426
+ @abstractmethod
1427
+ def _release(self) -> None:
1428
+ """Releases the lock and sets self._context.lock_file_fd to None."""
1429
+ raise NotImplementedError
1430
+
1431
+
1432
+ # acquire() returns this wrapper instead of self so entering the with-statement does not call __enter__ a second
1433
+ # time; returning self would re-acquire the lock in BaseFileLock.__enter__ without a matching release (issue #37).
1434
+ class AcquireReturnProxy:
1435
+ """A context-aware object that will release the lock file when exiting."""
1436
+
1437
+ def __init__(self, lock: BaseFileLock | ReadWriteLock | SoftReadWriteLock) -> None:
1438
+ self.lock: BaseFileLock | ReadWriteLock | SoftReadWriteLock = lock
1439
+
1440
+ def __enter__(self) -> BaseFileLock | ReadWriteLock | SoftReadWriteLock:
1441
+ return self.lock
1442
+
1443
+ def __exit__(
1444
+ self,
1445
+ exc_type: type[BaseException] | None,
1446
+ exc_value: BaseException | None,
1447
+ traceback: TracebackType | None,
1448
+ ) -> None:
1449
+ if isinstance(self.lock, BaseFileLock):
1450
+ self.lock._release_in_context(exc_value) # ruff:ignore[private-member-access] # forwards __exit__ to the owned lock's context release
1451
+ else: # a reader/writer lock does not carry a context_error_policy
1452
+ self.lock.release()
1453
+
1454
+
1455
+ @dataclass
1456
+ class FileLockContext:
1457
+ """Holds the context for a ``BaseFileLock`` object."""
1458
+
1459
+ # A separate class so ThreadLocalFileContext can make the whole context thread-local.
1460
+
1461
+ lock_file: str
1462
+ timeout: float
1463
+ mode: int
1464
+ blocking: bool
1465
+ poll_interval: float
1466
+
1467
+ #: The lock lifetime in seconds; ``None`` means the lock never expires.
1468
+ lifetime: float | None = None
1469
+
1470
+ #: File descriptor from os.open for the lock file; not None while the lock is held.
1471
+ lock_file_fd: int | None = None
1472
+
1473
+ #: Registry token for the descriptor owned by this thread's context.
1474
+ lock_file_fd_token: int | None = None
1475
+
1476
+ #: Identity captured by a backend that already inspected the descriptor.
1477
+ lock_file_fd_identity: tuple[int, int] | None = None
1478
+
1479
+ #: Descriptor opened by a backend but not yet committed as the held lock.
1480
+ pending_lock_file_fd: int | None = None
1481
+
1482
+ #: Identity captured for a descriptor whose acquisition has not committed.
1483
+ pending_lock_file_fd_identity: tuple[int, int] | None = None
1484
+
1485
+ #: Depth of nested acquisitions; the lock is released only when it returns to 0.
1486
+ lock_counter: int = 0
1487
+
1488
+ #: Canonical registry key captured when the first physical acquisition commits.
1489
+ lock_file_key: Hashable | None = None
1490
+
1491
+ #: Claim pathnames this owner published, removed by name on release so no holder ever unlinks a peer's claim.
1492
+ owner_claim_paths: tuple[str, ...] = ()
1493
+
1494
+ #: Canonical lock path resolved when an acquisition starts. A waiter polling a relative path must keep publishing
1495
+ #: into the directory it started in, even when another thread changes the working directory mid-wait.
1496
+ claim_root: str | None = None
1497
+
1498
+
1499
+ class ThreadLocalFileContext(FileLockContext, local):
1500
+ """A thread local version of the ``FileLockContext`` class."""
1501
+
1502
+
1503
+ @dataclass(frozen=True)
1504
+ class _OwnedDescriptor:
1505
+ fd: int
1506
+ creator_pid: int
1507
+ device: int | None
1508
+ inode: int | None
1509
+
1510
+
1511
+ class _ForkTransitionContext(local):
1512
+ depth: int = 0
1513
+
1514
+
1515
+ class _ForkState:
1516
+ def __init__(self) -> None:
1517
+ self.gate = Condition(RLock())
1518
+ self.registry_lock = RLock()
1519
+ self.parameter_models_lock = RLock()
1520
+ self.transition_context = _ForkTransitionContext()
1521
+ self.transitions: dict[int, dict[int, _ForkDescriptorOwner | None]] = {}
1522
+ self.active_transitions = 0
1523
+ self.admission_closed = False
1524
+ self.fork_owner_depths: dict[int, int] = {}
1525
+ self.pinned_objects: dict[int, list[tuple[_ForkResettable, ...]]] = {}
1526
+ self.pinned_classes: dict[int, list[tuple[_ForkResettableClass, ...]]] = {}
1527
+ self.provisional_descriptor_tokens: dict[int, list[tuple[int, ...]]] = {}
1528
+ self.pid = os.getpid()
1529
+
1530
+ def reset_synchronization(self) -> None: # pragma: forked child
1531
+ self.gate = Condition(RLock())
1532
+ self.registry_lock = RLock()
1533
+ self.parameter_models_lock = RLock()
1534
+ self.transition_context = _ForkTransitionContext()
1535
+ self.transitions = {}
1536
+ self.active_transitions = 0
1537
+ self.admission_closed = False
1538
+ self.fork_owner_depths = {}
1539
+ self.pinned_objects = {}
1540
+ self.pinned_classes = {}
1541
+ self.provisional_descriptor_tokens = {}
1542
+
1543
+
1544
+ _FORK_OBJECTS: Final[WeakValueDictionary[int, _ForkResettable]] = WeakValueDictionary()
1545
+ _FORK_CLASSES: Final[WeakValueDictionary[int, _ForkResettableClass]] = WeakValueDictionary()
1546
+ _OWNED_DESCRIPTORS: Final[dict[int, _OwnedDescriptor]] = {}
1547
+ _DESCRIPTOR_TOKENS: Final[count[int]] = count()
1548
+ _TRANSITION_TOKENS: Final[count[int]] = count()
1549
+ _FORK_STATE: Final = _ForkState()
1550
+ _FORK_AUDIT_EVENTS: Final[frozenset[str]] = frozenset({"os.fork", "os.forkpty"})
1551
+
1552
+
1553
+ def _register_fork_hooks() -> None:
1554
+ if _REGISTER_AT_FORK is None:
1555
+ return # pragma: lacks fork
1556
+ sys.addaudithook(_audit_fork_safety) # pragma: needs fork
1557
+ _REGISTER_AT_FORK( # pragma: needs fork
1558
+ before=_pin_fork_objects,
1559
+ after_in_parent=_resume_parent_after_fork,
1560
+ after_in_child=_reset_child_after_fork,
1561
+ )
1562
+
1563
+
1564
+ @contextmanager
1565
+ def _fork_transition(descriptor_owner: _ForkDescriptorOwner | None = None) -> Generator[None]:
1566
+ if not _HAS_REGISTER_AT_FORK:
1567
+ yield # pragma: lacks fork
1568
+ return # pragma: lacks fork
1569
+ _ensure_current_process() # pragma: needs fork
1570
+ creator_pid = os.getpid() # pragma: needs fork
1571
+ token = _enter_fork_transition(descriptor_owner) # pragma: needs fork
1572
+ try: # pragma: needs fork
1573
+ yield
1574
+ finally:
1575
+ if os.getpid() == creator_pid: # pragma: needs fork
1576
+ _leave_fork_transition(token)
1577
+
1578
+
1579
+ def _register_fork_object(instance: _ForkResettable) -> None:
1580
+ if not _HAS_REGISTER_AT_FORK:
1581
+ return # pragma: lacks fork
1582
+ with _fork_transition(), _FORK_STATE.registry_lock: # pragma: needs fork
1583
+ _FORK_OBJECTS[id(instance)] = instance
1584
+ _refresh_owner_pins()
1585
+
1586
+
1587
+ def _register_fork_class(cls: _ForkResettableClass) -> None:
1588
+ if not _HAS_REGISTER_AT_FORK:
1589
+ return # pragma: lacks fork
1590
+ with _fork_transition(), _FORK_STATE.registry_lock: # pragma: needs fork
1591
+ _FORK_CLASSES[id(cls)] = cls
1592
+ _refresh_owner_pins()
1593
+
1594
+
1595
+ def _register_owned_descriptor(fd: int, identity: tuple[int, int] | None = None) -> int | None:
1596
+ if not _HAS_REGISTER_AT_FORK:
1597
+ return None # pragma: lacks fork
1598
+ with _fork_transition(): # pragma: needs fork
1599
+ if identity is None:
1600
+ stat_result = os.fstat(fd)
1601
+ identity = stat_result.st_dev, stat_result.st_ino
1602
+ return _record_owned_descriptor(fd, identity)
1603
+
1604
+
1605
+ def _register_unverified_owned_descriptor(fd: int) -> int | None:
1606
+ if not _HAS_REGISTER_AT_FORK:
1607
+ return None # pragma: lacks fork
1608
+ with _fork_transition(): # pragma: needs fork
1609
+ return _record_owned_descriptor(fd, None)
1610
+
1611
+
1612
+ def _record_owned_descriptor(fd: int, identity: tuple[int, int] | None) -> int: # pragma: needs fork
1613
+ with _FORK_STATE.registry_lock:
1614
+ token = next(_DESCRIPTOR_TOKENS)
1615
+ _OWNED_DESCRIPTORS[token] = _OwnedDescriptor(
1616
+ fd=fd,
1617
+ creator_pid=os.getpid(),
1618
+ device=None if identity is None else identity[0],
1619
+ inode=None if identity is None else identity[1],
1620
+ )
1621
+ return token
1622
+
1623
+
1624
+ def _unregister_owned_descriptor(token: int) -> None: # pragma: needs fork
1625
+ with _fork_transition(), _FORK_STATE.registry_lock:
1626
+ _OWNED_DESCRIPTORS.pop(token, None)
1627
+
1628
+
1629
+ def _pin_fork_objects() -> None: # pragma: needs fork
1630
+ _ensure_current_process()
1631
+ thread_id = get_ident()
1632
+ with _FORK_STATE.gate:
1633
+ _FORK_STATE.fork_owner_depths[thread_id] = _FORK_STATE.fork_owner_depths.get(thread_id, 0) + 1
1634
+ _FORK_STATE.admission_closed = True
1635
+ while _FORK_STATE.active_transitions > len(_FORK_STATE.transitions.get(thread_id, ())):
1636
+ _FORK_STATE.gate.wait()
1637
+ transition_owners = tuple(_FORK_STATE.transitions.get(thread_id, {}).values())
1638
+ _verify_unverified_descriptors()
1639
+ owners = {id(owner): owner for owner in transition_owners if owner is not None}
1640
+ provisional_descriptor_tokens = tuple(
1641
+ starmap(
1642
+ _snapshot_descriptor_for_fork,
1643
+ (descriptor for owner in owners.values() for descriptor in owner._descriptors_for_fork()), # ruff:ignore[private-member-access] # snapshots each owner's own fork descriptors
1644
+ )
1645
+ )
1646
+ with _FORK_STATE.registry_lock:
1647
+ _FORK_STATE.provisional_descriptor_tokens.setdefault(thread_id, []).append(provisional_descriptor_tokens)
1648
+ _FORK_STATE.pinned_objects.setdefault(thread_id, []).append(tuple(_FORK_OBJECTS.values()))
1649
+ _FORK_STATE.pinned_classes.setdefault(thread_id, []).append(tuple(_FORK_CLASSES.values()))
1650
+
1651
+
1652
+ def _resume_parent_after_fork() -> None: # pragma: needs fork
1653
+ thread_id = get_ident()
1654
+ with _FORK_STATE.registry_lock:
1655
+ for token in _FORK_STATE.provisional_descriptor_tokens[thread_id].pop():
1656
+ _OWNED_DESCRIPTORS.pop(token, None)
1657
+ _FORK_STATE.pinned_objects[thread_id].pop()
1658
+ _FORK_STATE.pinned_classes[thread_id].pop()
1659
+ if not _FORK_STATE.provisional_descriptor_tokens[thread_id]: # pragma: needs fork
1660
+ del _FORK_STATE.provisional_descriptor_tokens[thread_id]
1661
+ del _FORK_STATE.pinned_objects[thread_id]
1662
+ del _FORK_STATE.pinned_classes[thread_id]
1663
+ with _FORK_STATE.gate:
1664
+ if _FORK_STATE.fork_owner_depths[thread_id] == 1:
1665
+ del _FORK_STATE.fork_owner_depths[thread_id]
1666
+ else: # pragma: no cover - earlier at-fork callbacks may deadlock first
1667
+ _FORK_STATE.fork_owner_depths[thread_id] -= 1
1668
+ _FORK_STATE.admission_closed = bool(_FORK_STATE.fork_owner_depths)
1669
+ _FORK_STATE.gate.notify_all()
1670
+
1671
+
1672
+ def _ensure_current_process() -> None:
1673
+ _reset_child_after_fork()
1674
+
1675
+
1676
+ def _reset_child_after_fork() -> None: # pragma: forked child
1677
+ if (pid := os.getpid()) == _FORK_STATE.pid:
1678
+ return
1679
+ thread_id = get_ident()
1680
+ pinned_objects = _FORK_STATE.pinned_objects.get(thread_id, [()])[-1]
1681
+ pinned_classes = _FORK_STATE.pinned_classes.get(thread_id, [()])[-1]
1682
+ descriptors: list[_OwnedDescriptor] = []
1683
+ for token, descriptor in tuple(_OWNED_DESCRIPTORS.items()):
1684
+ if descriptor.creator_pid != pid:
1685
+ descriptors.append(_OWNED_DESCRIPTORS.pop(token))
1686
+ _FORK_STATE.reset_synchronization()
1687
+ _FORK_STATE.pid = pid
1688
+ _INIT_PARAMETER_MODELS.clear()
1689
+ _detach_child_state(descriptors, pinned_objects, pinned_classes)
1690
+
1691
+
1692
+ def _enter_fork_transition(descriptor_owner: _ForkDescriptorOwner | None) -> int: # pragma: needs fork
1693
+ thread_id = get_ident()
1694
+ with _FORK_STATE.gate:
1695
+ while (
1696
+ _FORK_STATE.admission_closed
1697
+ and thread_id not in _FORK_STATE.fork_owner_depths
1698
+ and thread_id not in _FORK_STATE.transitions
1699
+ ):
1700
+ _FORK_STATE.gate.wait() # pragma: no cover - exercised in isolated interpreter
1701
+ token = next(_TRANSITION_TOKENS)
1702
+ _FORK_STATE.transitions.setdefault(thread_id, {})[token] = descriptor_owner
1703
+ _FORK_STATE.active_transitions += 1
1704
+ _FORK_STATE.transition_context.depth += 1
1705
+ return token
1706
+
1707
+
1708
+ def _leave_fork_transition(token: int) -> None: # pragma: needs fork
1709
+ _FORK_STATE.transition_context.depth -= 1
1710
+ with _FORK_STATE.gate:
1711
+ thread_id = get_ident()
1712
+ del _FORK_STATE.transitions[thread_id][token]
1713
+ if not _FORK_STATE.transitions[thread_id]:
1714
+ del _FORK_STATE.transitions[thread_id]
1715
+ _FORK_STATE.active_transitions -= 1
1716
+ _FORK_STATE.gate.notify_all()
1717
+
1718
+
1719
+ def _verify_unverified_descriptors() -> None: # pragma: needs fork
1720
+ with _FORK_STATE.registry_lock:
1721
+ for token, descriptor in tuple(_OWNED_DESCRIPTORS.items()):
1722
+ if descriptor.creator_pid != os.getpid() or descriptor.device is not None:
1723
+ continue
1724
+ try:
1725
+ stat_result = os.fstat(descriptor.fd)
1726
+ except OSError:
1727
+ continue
1728
+ _OWNED_DESCRIPTORS[token] = _OwnedDescriptor(
1729
+ fd=descriptor.fd,
1730
+ creator_pid=descriptor.creator_pid,
1731
+ device=stat_result.st_dev,
1732
+ inode=stat_result.st_ino,
1733
+ )
1734
+
1735
+
1736
+ def _snapshot_descriptor_for_fork(fd: int, identity: tuple[int, int] | None) -> int: # pragma: needs fork
1737
+ if identity is None: # pragma: needs fork
1738
+ try:
1739
+ stat_result = os.fstat(fd)
1740
+ except OSError:
1741
+ pass
1742
+ else:
1743
+ identity = stat_result.st_dev, stat_result.st_ino
1744
+ return _record_owned_descriptor(fd, identity)
1745
+
1746
+
1747
+ def _detach_child_state( # pragma: forked child
1748
+ descriptors: list[_OwnedDescriptor],
1749
+ pinned_objects: tuple[_ForkResettable, ...],
1750
+ pinned_classes: tuple[_ForkResettableClass, ...],
1751
+ ) -> None:
1752
+ for descriptor in descriptors:
1753
+ if descriptor.device is None:
1754
+ continue
1755
+ try:
1756
+ stat_result = os.fstat(descriptor.fd)
1757
+ except OSError:
1758
+ continue
1759
+ if (stat_result.st_dev, stat_result.st_ino) != (descriptor.device, descriptor.inode):
1760
+ continue
1761
+ with contextlib.suppress(OSError):
1762
+ os.close(descriptor.fd)
1763
+ for instance in pinned_objects:
1764
+ instance._reset_after_fork_in_child() # ruff:ignore[private-member-access] # resets each pinned instance in the fork child
1765
+ for cls in pinned_classes:
1766
+ cls._reset_class_after_fork()
1767
+ _registry.held.clear()
1768
+
1769
+
1770
+ def _refresh_owner_pins() -> None: # pragma: needs fork
1771
+ with _FORK_STATE.gate:
1772
+ fork_owner_thread_ids = tuple(_FORK_STATE.fork_owner_depths)
1773
+ if get_ident() not in fork_owner_thread_ids: # pragma: no cover - at-fork callbacks disable tracing
1774
+ return
1775
+ objects = tuple(_FORK_OBJECTS.values())
1776
+ classes = tuple(_FORK_CLASSES.values())
1777
+ for thread_id in fork_owner_thread_ids:
1778
+ if object_snapshots := _FORK_STATE.pinned_objects.get(thread_id): # pragma: needs fork
1779
+ object_snapshots[:] = [objects] * len(object_snapshots)
1780
+ _FORK_STATE.pinned_classes[thread_id][:] = [classes] * len(object_snapshots)
1781
+
1782
+
1783
+ # The defaults capture the module globals: the hook outlives them at interpreter shutdown, where CPython wipes the
1784
+ # module dict to None before the final audit events fire.
1785
+ def _audit_fork_safety( # pragma: no cover - CPython disables tracing while Python audit hooks run
1786
+ event: str,
1787
+ _args: Unused,
1788
+ *,
1789
+ _fork_events: frozenset[str] = _FORK_AUDIT_EVENTS,
1790
+ _state: _ForkState = _FORK_STATE,
1791
+ ) -> None:
1792
+ if event in _fork_events:
1793
+ if _state.transition_context.depth or _state.fork_owner_depths:
1794
+ msg = f"{event} is unsafe while filelock is changing descriptor ownership"
1795
+ raise RuntimeError(msg)
1796
+ elif event == "_posixsubprocess.fork_exec" and _state.transition_context.depth:
1797
+ msg = "fork_exec is unsafe while filelock is changing descriptor ownership"
1798
+ raise RuntimeError(msg)
1799
+
1800
+
1801
+ _register_fork_hooks()
1802
+
1803
+
1804
+ __all__ = [
1805
+ "_UNSET_FILE_MODE",
1806
+ "AcquireReturnProxy",
1807
+ "BaseFileLock",
1808
+ "CloseErrorPolicy",
1809
+ "ContextErrorPolicy",
1810
+ "FileLockContext",
1811
+ "FileLockMeta",
1812
+ "LockOptions",
1813
+ "_append_exception_context",
1814
+ "_canonical",
1815
+ "_ensure_current_process",
1816
+ "_fork_transition",
1817
+ "_grouped_errors",
1818
+ "_raise_body_and_release",
1819
+ "_raise_chained_errors",
1820
+ "_raise_cleanup_errors",
1821
+ "_raise_grouped_errors",
1822
+ "_register_fork_class",
1823
+ "_register_fork_object",
1824
+ "_register_owned_descriptor",
1825
+ "_unregister_owned_descriptor",
1826
+ ]
.venv/lib/python3.12/site-packages/filelock/_async.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Separate caller cancellation from backend task and executor-future results."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import time
8
+ from concurrent.futures import Future as ConcurrentFuture
9
+ from dataclasses import dataclass
10
+ from threading import Lock
11
+ from typing import TYPE_CHECKING, Final, Generic, NoReturn, TypeVar, cast
12
+
13
+ from ._api import _append_exception_context, _raise_chained_errors
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import AsyncIterator, Awaitable, Callable
17
+
18
+ _T = TypeVar("_T")
19
+
20
+
21
+ class _AsyncTransitionUnavailableError(Exception):
22
+ pass
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class _BackendOutcome(Generic[_T]):
27
+ value: _T | None = None
28
+ error: BaseException | None = None
29
+
30
+
31
+ class _AsyncTransitionGate:
32
+ def __init__(self) -> None:
33
+ self._tail_lock: Final[Lock] = Lock()
34
+ self._tail: ConcurrentFuture[None] | None = None
35
+
36
+ @contextlib.asynccontextmanager
37
+ async def hold(self) -> AsyncIterator[None]:
38
+ ticket: ConcurrentFuture[None] = ConcurrentFuture()
39
+ with self._tail_lock:
40
+ predecessor = self._tail
41
+ self._tail = ticket
42
+ if predecessor is not None:
43
+ try:
44
+ await _wait_until_done(asyncio.wrap_future(predecessor))
45
+ except asyncio.CancelledError:
46
+ predecessor.add_done_callback(lambda _predecessor: self._leave(ticket))
47
+ raise
48
+ try:
49
+ yield
50
+ finally:
51
+ self._leave(ticket)
52
+
53
+ @contextlib.asynccontextmanager
54
+ async def hold_for_acquire(
55
+ self,
56
+ *,
57
+ blocking: bool,
58
+ cancel_check: Callable[[], bool] | None,
59
+ deadline: float | None,
60
+ poll_interval: float,
61
+ ) -> AsyncIterator[None]:
62
+ ticket: ConcurrentFuture[None] = ConcurrentFuture()
63
+ with self._tail_lock:
64
+ predecessor = self._tail
65
+ self._tail = ticket
66
+ if predecessor is not None and not predecessor.done():
67
+ try:
68
+ await self._wait_for_predecessor(
69
+ predecessor,
70
+ blocking=blocking,
71
+ cancel_check=cancel_check,
72
+ deadline=deadline,
73
+ poll_interval=poll_interval,
74
+ )
75
+ except BaseException:
76
+ predecessor.add_done_callback(lambda _predecessor: self._leave(ticket))
77
+ raise
78
+ try:
79
+ yield
80
+ finally:
81
+ self._leave(ticket)
82
+
83
+ @staticmethod
84
+ async def _wait_for_predecessor(
85
+ predecessor: ConcurrentFuture[None],
86
+ *,
87
+ blocking: bool,
88
+ cancel_check: Callable[[], bool] | None,
89
+ deadline: float | None,
90
+ poll_interval: float,
91
+ ) -> None:
92
+ if not blocking:
93
+ raise _AsyncTransitionUnavailableError
94
+ waiter = asyncio.wrap_future(predecessor)
95
+ while not predecessor.done():
96
+ if cancel_check is not None and cancel_check():
97
+ raise _AsyncTransitionUnavailableError
98
+ if deadline is not None:
99
+ if (remaining := deadline - time.perf_counter()) <= 0:
100
+ raise _AsyncTransitionUnavailableError
101
+ wait_interval = min(poll_interval, remaining) if cancel_check is not None else remaining
102
+ else:
103
+ wait_interval = poll_interval if cancel_check is not None else None
104
+ await asyncio.wait((waiter,), timeout=wait_interval)
105
+
106
+ def _leave(self, ticket: ConcurrentFuture[None]) -> None:
107
+ with self._tail_lock:
108
+ if self._tail is ticket:
109
+ self._tail = None
110
+ ticket.set_result(None)
111
+
112
+
113
+ async def _drain_future(future: asyncio.Future[_BackendOutcome[_T]]) -> _T:
114
+ while not future.done():
115
+ with contextlib.suppress(asyncio.CancelledError):
116
+ await _wait_until_done(future)
117
+ return _future_result(future)
118
+
119
+
120
+ async def _wait_until_done(future: asyncio.Future[_T]) -> None:
121
+ if not future.done():
122
+ await asyncio.wait((future,))
123
+
124
+
125
+ def _future_result(future: asyncio.Future[_BackendOutcome[_T]]) -> _T:
126
+ outcome = future.result()
127
+ if (error := outcome.error) is None:
128
+ return cast("_T", outcome.value)
129
+ context = error.__context__
130
+ try:
131
+ raise error # ruff:ignore[raise-within-try] # the handler restores context changed across the async boundary
132
+ except BaseException:
133
+ error.__context__ = context
134
+ raise
135
+
136
+
137
+ def _capture_call(func: Callable[[], _T]) -> _BackendOutcome[_T]:
138
+ try:
139
+ return _BackendOutcome(value=func())
140
+ except BaseException as error: # ruff:ignore[blind-except] # backend control-flow exceptions are operation results
141
+ return _BackendOutcome(error=error)
142
+
143
+
144
+ def _raise_cancelled_error(cancellation: asyncio.CancelledError, error: BaseException) -> NoReturn:
145
+ # A reconciliation step failed while unwinding a cancellation, so keep both exception chains. Splice the error's
146
+ # existing context onto the cancellation, then make the cancellation the error's context, so both the failure and
147
+ # the cancellation that triggered it survive. Shared by the async wrappers so cancellations report the same way.
148
+ if (context := error.__context__) is not None and context is not cancellation:
149
+ if (cancellation_context := cancellation.__context__) is not None:
150
+ _append_exception_context(context, cancellation_context)
151
+ cancellation.__context__ = context
152
+ error.__context__ = cancellation
153
+ _raise_chained_errors(error)
154
+
155
+
156
+ async def _capture_awaitable(awaitable: Awaitable[_T]) -> _BackendOutcome[_T]:
157
+ try:
158
+ return _BackendOutcome(value=await awaitable)
159
+ except BaseException as error: # ruff:ignore[blind-except] # backend cancellation must remain distinct from caller cancellation
160
+ return _BackendOutcome(error=error)
161
+
162
+
163
+ __all__ = [
164
+ "_AsyncTransitionGate",
165
+ "_AsyncTransitionUnavailableError",
166
+ "_BackendOutcome",
167
+ "_capture_awaitable",
168
+ "_capture_call",
169
+ "_drain_future",
170
+ "_future_result",
171
+ "_raise_cancelled_error",
172
+ "_wait_until_done",
173
+ ]
.venv/lib/python3.12/site-packages/filelock/_async_read_write.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async wrapper around :class:`ReadWriteLock` for use with ``asyncio``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import functools
7
+ import os
8
+ import sqlite3
9
+ from concurrent.futures import ThreadPoolExecutor
10
+ from contextlib import asynccontextmanager
11
+ from typing import TYPE_CHECKING, ParamSpec, TypeVar
12
+
13
+ from ._api import (
14
+ _append_exception_context,
15
+ _ensure_current_process,
16
+ _fork_transition,
17
+ _register_fork_object,
18
+ )
19
+ from ._async import (
20
+ _BackendOutcome,
21
+ _capture_call,
22
+ _drain_future,
23
+ _future_result,
24
+ _raise_cancelled_error,
25
+ _wait_until_done,
26
+ )
27
+ from ._read_write import ReadWriteLock
28
+
29
+ if TYPE_CHECKING:
30
+ from collections.abc import AsyncGenerator, Callable
31
+ from concurrent import futures
32
+ from types import TracebackType
33
+
34
+ from ._api import AcquireReturnProxy
35
+
36
+ _P = ParamSpec("_P")
37
+ _R = TypeVar("_R")
38
+
39
+
40
+ class AsyncReadWriteLock:
41
+ """
42
+ Async wrapper around :class:`ReadWriteLock` for use in ``asyncio`` applications.
43
+
44
+ This wrapper dispatches every blocking SQLite operation to a thread pool via ``loop.run_in_executor()`` because
45
+ Python's :mod:`sqlite3` module has no async API. It delegates reentrancy, upgrade/downgrade rules, and singleton
46
+ behavior to the underlying :class:`ReadWriteLock`.
47
+
48
+ :param lock_file: path to the SQLite database file used as the lock
49
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
50
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
51
+ :param is_singleton: if ``True``, reuse existing :class:`ReadWriteLock` instances for the same resolved path
52
+ :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop
53
+ :param executor: executor for ``run_in_executor``. When ``None`` this lock creates and owns a dedicated
54
+ single-thread executor so every operation runs on the same thread (SQLite affinity requires this) and shuts it
55
+ down in :meth:`close`. This lock uses a caller-supplied executor as-is and never shuts it down, so after passing
56
+ no executor call :meth:`close` to release the owned one.
57
+
58
+ .. versionadded:: 3.21.0
59
+
60
+ """
61
+
62
+ def __init__( # ruff:ignore[too-many-arguments] # public constructor: one parameter per documented lock option
63
+ self,
64
+ lock_file: str | os.PathLike[str],
65
+ timeout: float = -1,
66
+ *,
67
+ blocking: bool = True,
68
+ is_singleton: bool = True,
69
+ loop: asyncio.AbstractEventLoop | None = None,
70
+ executor: futures.Executor | None = None,
71
+ ) -> None:
72
+ creator_pid = os.getpid()
73
+ self._creator_pid = creator_pid
74
+ self._fork_invalidated = False
75
+ self._closed = False
76
+ _register_fork_object(self)
77
+ with _fork_transition():
78
+ self._lock = ReadWriteLock(lock_file, timeout, blocking=blocking, is_singleton=is_singleton)
79
+ self._loop = loop
80
+ self._owns_executor = executor is None
81
+ self._executor = executor or ThreadPoolExecutor(max_workers=1)
82
+ if os.getpid() != creator_pid: # pragma: forked child
83
+ msg = "AsyncReadWriteLock construction cannot continue after fork"
84
+ raise RuntimeError(msg)
85
+
86
+ @property
87
+ def lock_file(self) -> str:
88
+ """The path to the lock file."""
89
+ return self._lock.lock_file
90
+
91
+ @property
92
+ def timeout(self) -> float:
93
+ """The default timeout."""
94
+ return self._lock.timeout
95
+
96
+ @property
97
+ def blocking(self) -> bool:
98
+ """Whether blocking is enabled by default."""
99
+ return self._lock.blocking
100
+
101
+ @property
102
+ def loop(self) -> asyncio.AbstractEventLoop | None:
103
+ """The event loop (or ``None`` for the running loop)."""
104
+ return self._loop
105
+
106
+ @property
107
+ def executor(self) -> futures.Executor:
108
+ """The executor used for ``run_in_executor`` (a dedicated single-thread one if none was supplied)."""
109
+ return self._executor
110
+
111
+ @asynccontextmanager
112
+ async def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]:
113
+ """
114
+ Async context manager that acquires and releases a shared read lock.
115
+
116
+ Falls back to instance defaults for *timeout* and *blocking* when ``None``.
117
+
118
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
119
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
120
+
121
+ """
122
+ if timeout is None:
123
+ timeout = self._lock.timeout
124
+ if blocking is None:
125
+ blocking = self._lock.blocking
126
+ await self.acquire_read(timeout, blocking=blocking)
127
+ body_error: BaseException | None = None
128
+ try:
129
+ yield
130
+ except BaseException as error:
131
+ body_error = error
132
+ raise
133
+ finally:
134
+ await self._release_in_context(body_error)
135
+
136
+ @asynccontextmanager
137
+ async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]:
138
+ """
139
+ Async context manager that acquires and releases an exclusive write lock.
140
+
141
+ Falls back to instance defaults for *timeout* and *blocking* when ``None``.
142
+
143
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
144
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
145
+
146
+ """
147
+ if timeout is None:
148
+ timeout = self._lock.timeout
149
+ if blocking is None:
150
+ blocking = self._lock.blocking
151
+ await self.acquire_write(timeout, blocking=blocking)
152
+ body_error: BaseException | None = None
153
+ try:
154
+ yield
155
+ except BaseException as error:
156
+ body_error = error
157
+ raise
158
+ finally:
159
+ await self._release_in_context(body_error)
160
+
161
+ async def _release_in_context(self, body_error: BaseException | None) -> None:
162
+ try:
163
+ await self.release()
164
+ except BaseException as release_error:
165
+ if body_error is not None:
166
+ _append_exception_context(release_error, body_error)
167
+ raise
168
+
169
+ async def acquire_read(self, timeout: float = -1, *, blocking: bool = True) -> AsyncAcquireReadWriteReturnProxy:
170
+ """
171
+ Acquire a shared read lock.
172
+
173
+ See :meth:`ReadWriteLock.acquire_read` for full semantics.
174
+
175
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
176
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
177
+
178
+ :returns: a proxy that can be used as an async context manager to release the lock
179
+
180
+ :raises RuntimeError: if a write lock is already held on this instance
181
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
182
+
183
+ """
184
+ self._raise_if_unusable()
185
+ await self._run_acquire(functools.partial(self._lock.acquire_read, timeout, blocking=blocking))
186
+ return AsyncAcquireReadWriteReturnProxy(lock=self)
187
+
188
+ async def acquire_write(self, timeout: float = -1, *, blocking: bool = True) -> AsyncAcquireReadWriteReturnProxy:
189
+ """
190
+ Acquire an exclusive write lock.
191
+
192
+ See :meth:`ReadWriteLock.acquire_write` for full semantics.
193
+
194
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
195
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
196
+
197
+ :returns: a proxy that can be used as an async context manager to release the lock
198
+
199
+ :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread
200
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
201
+
202
+ """
203
+ self._raise_if_unusable()
204
+ await self._run_acquire(functools.partial(self._lock.acquire_write, timeout, blocking=blocking))
205
+ return AsyncAcquireReadWriteReturnProxy(lock=self)
206
+
207
+ async def release(self, *, force: bool = False) -> None:
208
+ """
209
+ Release one level of the current lock.
210
+
211
+ See :meth:`ReadWriteLock.release` for full semantics.
212
+
213
+ :param force: if ``True``, release the lock completely regardless of the current lock level
214
+
215
+ :raises RuntimeError: if no lock is currently held and *force* is ``False``
216
+
217
+ """
218
+ _ensure_current_process()
219
+ if self._inherited: # pragma: needs fork
220
+ return
221
+ await self._run(self._lock.release, force=force)
222
+
223
+ async def close(self) -> None:
224
+ """
225
+ Release the lock (if held) and close the underlying SQLite connection.
226
+
227
+ After calling this method, the lock instance is no longer usable.
228
+
229
+ """
230
+ _ensure_current_process()
231
+ if self._inherited: # pragma: needs fork
232
+ return
233
+ if self._closed:
234
+ return
235
+ close_future = self._submit(self._lock.close)
236
+ try:
237
+ await _wait_until_done(close_future)
238
+ except asyncio.CancelledError as cancellation:
239
+ try:
240
+ await _drain_future(close_future)
241
+ except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below
242
+ _raise_cancelled_error(cancellation, error)
243
+ self._closed = True
244
+ self._shutdown_owned_executor()
245
+ raise
246
+ _future_result(close_future)
247
+ self._closed = True
248
+ # Wait for the worker to exit rather than letting it drain in the background: a caller that forks right
249
+ # after closing deserves a single-threaded process, and os.fork warns about any surviving thread.
250
+ if self._owns_executor:
251
+ await asyncio.to_thread(functools.partial(self._executor.shutdown, wait=True))
252
+
253
+ async def _run_acquire(self, acquire: Callable[[], AcquireReturnProxy]) -> None:
254
+ acquire_future = self._submit(acquire)
255
+ try:
256
+ await _wait_until_done(acquire_future)
257
+ except asyncio.CancelledError as cancellation:
258
+ try:
259
+ await _drain_future(acquire_future)
260
+ except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below
261
+ _raise_cancelled_error(cancellation, error)
262
+ try:
263
+ await _drain_future(self._submit(self._lock.release))
264
+ except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below
265
+ _raise_cancelled_error(cancellation, error)
266
+ raise
267
+ _future_result(acquire_future)
268
+
269
+ async def _run(self, func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R:
270
+ future = self._submit(func, *args, **kwargs)
271
+ try:
272
+ await _wait_until_done(future)
273
+ except asyncio.CancelledError as cancellation:
274
+ try:
275
+ await _drain_future(future)
276
+ except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below
277
+ _raise_cancelled_error(cancellation, error)
278
+ raise
279
+ return _future_result(future)
280
+
281
+ def _submit(
282
+ self, func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs
283
+ ) -> asyncio.Future[_BackendOutcome[_R]]:
284
+ return (self._loop or asyncio.get_running_loop()).run_in_executor(
285
+ self._executor,
286
+ _capture_call,
287
+ functools.partial(func, *args, **kwargs),
288
+ )
289
+
290
+ def _shutdown_owned_executor(self) -> None:
291
+ if self._owns_executor:
292
+ self._executor.shutdown(wait=False)
293
+
294
+ @property
295
+ def _inherited(self) -> bool:
296
+ return self._fork_invalidated or os.getpid() != self._creator_pid
297
+
298
+ def _raise_if_unusable(self) -> None:
299
+ _ensure_current_process()
300
+ if self._inherited: # pragma: needs fork
301
+ msg = f"AsyncReadWriteLock on {self.lock_file} was invalidated by fork(); construct a new instance"
302
+ raise RuntimeError(msg)
303
+ if self._closed:
304
+ msg = "Cannot operate on a closed database."
305
+ raise sqlite3.ProgrammingError(msg)
306
+
307
+ def _reset_after_fork_in_child(self) -> None: # pragma: forked child
308
+ self._fork_invalidated = True
309
+
310
+ def __del__(self) -> None:
311
+ # Safety net when close() was never called: shut down the executor we own so its worker thread does not
312
+ # outlive the lock. shutdown(wait=False) never blocks.
313
+ if os.getpid() == getattr(self, "_creator_pid", None) and getattr(self, "_owns_executor", False):
314
+ self._executor.shutdown(wait=False)
315
+
316
+
317
+ class AsyncAcquireReadWriteReturnProxy:
318
+ """Context-aware object that releases the async read/write lock on exit."""
319
+
320
+ def __init__(self, lock: AsyncReadWriteLock) -> None:
321
+ self.lock = lock
322
+
323
+ async def __aenter__(self) -> AsyncReadWriteLock:
324
+ return self.lock
325
+
326
+ async def __aexit__(
327
+ self,
328
+ exc_type: type[BaseException] | None,
329
+ exc_value: BaseException | None,
330
+ traceback: TracebackType | None,
331
+ ) -> None:
332
+ await self.lock.release()
333
+
334
+
335
+ __all__ = [
336
+ "AsyncAcquireReadWriteReturnProxy",
337
+ "AsyncReadWriteLock",
338
+ ]