igerasimov commited on
Commit
b644922
·
verified ·
1 Parent(s): e80831e

Deploy Phase 2 dataset classifier (part 2)

Browse files

Source GitHub commit: 740750973b9c67c0d55c209c006d860192f79dc2

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. .venv/lib/python3.13/site-packages/aiofiles-24.1.0.dist-info/WHEEL +4 -0
  3. .venv/lib/python3.13/site-packages/aiofiles-24.1.0.dist-info/licenses/LICENSE +202 -0
  4. .venv/lib/python3.13/site-packages/aiofiles-24.1.0.dist-info/licenses/NOTICE +2 -0
  5. .venv/lib/python3.13/site-packages/annotated_doc-0.0.4.dist-info/INSTALLER +1 -0
  6. .venv/lib/python3.13/site-packages/annotated_doc-0.0.4.dist-info/METADATA +145 -0
  7. .venv/lib/python3.13/site-packages/annotated_doc-0.0.4.dist-info/RECORD +11 -0
  8. .venv/lib/python3.13/site-packages/annotated_doc-0.0.4.dist-info/WHEEL +4 -0
  9. .venv/lib/python3.13/site-packages/annotated_doc-0.0.4.dist-info/entry_points.txt +4 -0
  10. .venv/lib/python3.13/site-packages/annotated_doc-0.0.4.dist-info/licenses/LICENSE +21 -0
  11. .venv/lib/python3.13/site-packages/annotated_doc/__init__.py +3 -0
  12. .venv/lib/python3.13/site-packages/annotated_doc/main.py +36 -0
  13. .venv/lib/python3.13/site-packages/annotated_doc/py.typed +0 -0
  14. .venv/lib/python3.13/site-packages/annotated_types-0.7.0.dist-info/INSTALLER +1 -0
  15. .venv/lib/python3.13/site-packages/annotated_types-0.7.0.dist-info/METADATA +295 -0
  16. .venv/lib/python3.13/site-packages/annotated_types-0.7.0.dist-info/RECORD +10 -0
  17. .venv/lib/python3.13/site-packages/annotated_types-0.7.0.dist-info/WHEEL +4 -0
  18. .venv/lib/python3.13/site-packages/annotated_types-0.7.0.dist-info/licenses/LICENSE +21 -0
  19. .venv/lib/python3.13/site-packages/annotated_types/__init__.py +432 -0
  20. .venv/lib/python3.13/site-packages/annotated_types/py.typed +0 -0
  21. .venv/lib/python3.13/site-packages/annotated_types/test_cases.py +151 -0
  22. .venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/INSTALLER +1 -0
  23. .venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/METADATA +107 -0
  24. .venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/RECORD +96 -0
  25. .venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/WHEEL +5 -0
  26. .venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/entry_points.txt +2 -0
  27. .venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/licenses/LICENSE +20 -0
  28. .venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/scm_file_list.json +119 -0
  29. .venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/scm_version.json +8 -0
  30. .venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/top_level.txt +1 -0
  31. .venv/lib/python3.13/site-packages/anyio/__init__.py +115 -0
  32. .venv/lib/python3.13/site-packages/anyio/_backends/__init__.py +0 -0
  33. .venv/lib/python3.13/site-packages/anyio/_backends/_asyncio.py +0 -0
  34. .venv/lib/python3.13/site-packages/anyio/_backends/_trio.py +1468 -0
  35. .venv/lib/python3.13/site-packages/anyio/_core/__init__.py +0 -0
  36. .venv/lib/python3.13/site-packages/anyio/_core/_asyncio_selector_thread.py +167 -0
  37. .venv/lib/python3.13/site-packages/anyio/_core/_contextmanagers.py +200 -0
  38. .venv/lib/python3.13/site-packages/anyio/_core/_eventloop.py +240 -0
  39. .venv/lib/python3.13/site-packages/anyio/_core/_exceptions.py +177 -0
  40. .venv/lib/python3.13/site-packages/anyio/_core/_fileio.py +960 -0
  41. .venv/lib/python3.13/site-packages/anyio/_core/_resources.py +18 -0
  42. .venv/lib/python3.13/site-packages/anyio/_core/_signals.py +29 -0
  43. .venv/lib/python3.13/site-packages/anyio/_core/_sockets.py +1011 -0
  44. .venv/lib/python3.13/site-packages/anyio/_core/_streams.py +52 -0
  45. .venv/lib/python3.13/site-packages/anyio/_core/_subprocesses.py +196 -0
  46. .venv/lib/python3.13/site-packages/anyio/_core/_synchronization.py +772 -0
  47. .venv/lib/python3.13/site-packages/anyio/_core/_tasks.py +412 -0
  48. .venv/lib/python3.13/site-packages/anyio/_core/_tempfile.py +613 -0
  49. .venv/lib/python3.13/site-packages/anyio/_core/_testing.py +82 -0
  50. .venv/lib/python3.13/site-packages/anyio/_core/_typedattr.py +81 -0
.gitattributes CHANGED
@@ -7,3 +7,5 @@
7
  .venv/lib/python3.13/site-packages/PIL/_imagingft.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
8
  .venv/lib/python3.13/site-packages/PIL/_imagingmath.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
9
  .venv/lib/python3.13/site-packages/_brotli.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
7
  .venv/lib/python3.13/site-packages/PIL/_imagingft.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
8
  .venv/lib/python3.13/site-packages/PIL/_imagingmath.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
9
  .venv/lib/python3.13/site-packages/_brotli.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
10
+ .venv/lib/python3.13/site-packages/audioop/_audioop.abi3.so filter=lfs diff=lfs merge=lfs -text
11
+ .venv/lib/python3.13/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.13/site-packages/aiofiles-24.1.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.25.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.venv/lib/python3.13/site-packages/aiofiles-24.1.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
.venv/lib/python3.13/site-packages/aiofiles-24.1.0.dist-info/licenses/NOTICE ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Asyncio support for files
2
+ Copyright 2016 Tin Tvrtkovic
.venv/lib/python3.13/site-packages/annotated_doc-0.0.4.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv/lib/python3.13/site-packages/annotated_doc-0.0.4.dist-info/METADATA ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: annotated-doc
3
+ Version: 0.0.4
4
+ Summary: Document parameters, class attributes, return types, and variables inline, with Annotated.
5
+ Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= <tiangolo@gmail.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Intended Audience :: Information Technology
9
+ Classifier: Intended Audience :: System Administrators
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Topic :: Internet
14
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Classifier: Topic :: Software Development :: Libraries
17
+ Classifier: Topic :: Software Development
18
+ Classifier: Typing :: Typed
19
+ Classifier: Development Status :: 4 - Beta
20
+ Classifier: Intended Audience :: Developers
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.8
23
+ Classifier: Programming Language :: Python :: 3.9
24
+ Classifier: Programming Language :: Python :: 3.10
25
+ Classifier: Programming Language :: Python :: 3.11
26
+ Classifier: Programming Language :: Python :: 3.12
27
+ Classifier: Programming Language :: Python :: 3.13
28
+ Classifier: Programming Language :: Python :: 3.14
29
+ Project-URL: Homepage, https://github.com/fastapi/annotated-doc
30
+ Project-URL: Documentation, https://github.com/fastapi/annotated-doc
31
+ Project-URL: Repository, https://github.com/fastapi/annotated-doc
32
+ Project-URL: Issues, https://github.com/fastapi/annotated-doc/issues
33
+ Project-URL: Changelog, https://github.com/fastapi/annotated-doc/release-notes.md
34
+ Requires-Python: >=3.8
35
+ Description-Content-Type: text/markdown
36
+
37
+ # Annotated Doc
38
+
39
+ Document parameters, class attributes, return types, and variables inline, with `Annotated`.
40
+
41
+ <a href="https://github.com/fastapi/annotated-doc/actions?query=workflow%3ATest+event%3Apush+branch%3Amain" target="_blank">
42
+ <img src="https://github.com/fastapi/annotated-doc/actions/workflows/test.yml/badge.svg?event=push&branch=main" alt="Test">
43
+ </a>
44
+ <a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/annotated-doc" target="_blank">
45
+ <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/annotated-doc.svg" alt="Coverage">
46
+ </a>
47
+ <a href="https://pypi.org/project/annotated-doc" target="_blank">
48
+ <img src="https://img.shields.io/pypi/v/annotated-doc?color=%2334D058&label=pypi%20package" alt="Package version">
49
+ </a>
50
+ <a href="https://pypi.org/project/annotated-doc" target="_blank">
51
+ <img src="https://img.shields.io/pypi/pyversions/annotated-doc.svg?color=%2334D058" alt="Supported Python versions">
52
+ </a>
53
+
54
+ ## Installation
55
+
56
+ ```bash
57
+ pip install annotated-doc
58
+ ```
59
+
60
+ Or with `uv`:
61
+
62
+ ```Python
63
+ uv add annotated-doc
64
+ ```
65
+
66
+ ## Usage
67
+
68
+ Import `Doc` and pass a single literal string with the documentation for the specific parameter, class attribute, return type, or variable.
69
+
70
+ For example, to document a parameter `name` in a function `hi` you could do:
71
+
72
+ ```Python
73
+ from typing import Annotated
74
+
75
+ from annotated_doc import Doc
76
+
77
+ def hi(name: Annotated[str, Doc("Who to say hi to")]) -> None:
78
+ print(f"Hi, {name}!")
79
+ ```
80
+
81
+ You can also use it to document class attributes:
82
+
83
+ ```Python
84
+ from typing import Annotated
85
+
86
+ from annotated_doc import Doc
87
+
88
+ class User:
89
+ name: Annotated[str, Doc("The user's name")]
90
+ age: Annotated[int, Doc("The user's age")]
91
+ ```
92
+
93
+ The same way, you could document return types and variables, or anything that could have a type annotation with `Annotated`.
94
+
95
+ ## Who Uses This
96
+
97
+ `annotated-doc` was made for:
98
+
99
+ * [FastAPI](https://fastapi.tiangolo.com/)
100
+ * [Typer](https://typer.tiangolo.com/)
101
+ * [SQLModel](https://sqlmodel.tiangolo.com/)
102
+ * [Asyncer](https://asyncer.tiangolo.com/)
103
+
104
+ `annotated-doc` is supported by [griffe-typingdoc](https://github.com/mkdocstrings/griffe-typingdoc), which powers reference documentation like the one in the [FastAPI Reference](https://fastapi.tiangolo.com/reference/).
105
+
106
+ ## Reasons not to use `annotated-doc`
107
+
108
+ You are already comfortable with one of the existing docstring formats, like:
109
+
110
+ * Sphinx
111
+ * numpydoc
112
+ * Google
113
+ * Keras
114
+
115
+ Your team is already comfortable using them.
116
+
117
+ You prefer having the documentation about parameters all together in a docstring, separated from the code defining them.
118
+
119
+ You care about a specific set of users, using one specific editor, and that editor already has support for the specific docstring format you use.
120
+
121
+ ## Reasons to use `annotated-doc`
122
+
123
+ * No micro-syntax to learn for newcomers, it’s **just Python** syntax.
124
+ * **Editing** would be already fully supported by default by any editor (current or future) supporting Python syntax, including syntax errors, syntax highlighting, etc.
125
+ * **Rendering** would be relatively straightforward to implement by static tools (tools that don't need runtime execution), as the information can be extracted from the AST they normally already create.
126
+ * **Deduplication of information**: the name of a parameter would be defined in a single place, not duplicated inside of a docstring.
127
+ * **Elimination** of the possibility of having **inconsistencies** when removing a parameter or class variable and **forgetting to remove** its documentation.
128
+ * **Minimization** of the probability of adding a new parameter or class variable and **forgetting to add its documentation**.
129
+ * **Elimination** of the possibility of having **inconsistencies** between the **name** of a parameter in the **signature** and the name in the docstring when it is renamed.
130
+ * **Access** to the documentation string for each symbol at **runtime**, including existing (older) Python versions.
131
+ * A more formalized way to document other symbols, like type aliases, that could use Annotated.
132
+ * **Support** for apps using FastAPI, Typer and others.
133
+ * **AI Accessibility**: AI tools will have an easier way understanding each parameter as the distance from documentation to parameter is much closer.
134
+
135
+ ## History
136
+
137
+ I ([@tiangolo](https://github.com/tiangolo)) originally wanted for this to be part of the Python standard library (in [PEP 727](https://peps.python.org/pep-0727/)), but the proposal was withdrawn as there was a fair amount of negative feedback and opposition.
138
+
139
+ The conclusion was that this was better done as an external effort, in a third-party library.
140
+
141
+ So, here it is, with a simpler approach, as a third-party library, in a way that can be used by others, starting with FastAPI and friends.
142
+
143
+ ## License
144
+
145
+ This project is licensed under the terms of the MIT license.
.venv/lib/python3.13/site-packages/annotated_doc-0.0.4.dist-info/RECORD ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ annotated_doc-0.0.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ annotated_doc-0.0.4.dist-info/METADATA,sha256=Irm5KJua33dY2qKKAjJ-OhKaVBVIfwFGej_dSe3Z1TU,6566
3
+ annotated_doc-0.0.4.dist-info/RECORD,,
4
+ annotated_doc-0.0.4.dist-info/WHEEL,sha256=9P2ygRxDrTJz3gsagc0Z96ukrxjr-LFBGOgv3AuKlCA,90
5
+ annotated_doc-0.0.4.dist-info/entry_points.txt,sha256=6OYgBcLyFCUgeqLgnvMyOJxPCWzgy7se4rLPKtNonMs,34
6
+ annotated_doc-0.0.4.dist-info/licenses/LICENSE,sha256=__Fwd5pqy_ZavbQFwIfxzuF4ZpHkqWpANFF-SlBKDN8,1086
7
+ annotated_doc/__init__.py,sha256=VuyxxUe80kfEyWnOrCx_Bk8hybo3aKo6RYBlkBBYW8k,52
8
+ annotated_doc/__pycache__/__init__.cpython-313.pyc,,
9
+ annotated_doc/__pycache__/main.cpython-313.pyc,,
10
+ annotated_doc/main.py,sha256=5Zfvxv80SwwLqpRW73AZyZyiM4bWma9QWRbp_cgD20s,1075
11
+ annotated_doc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
.venv/lib/python3.13/site-packages/annotated_doc-0.0.4.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: pdm-backend (2.4.5)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.venv/lib/python3.13/site-packages/annotated_doc-0.0.4.dist-info/entry_points.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [console_scripts]
2
+
3
+ [gui_scripts]
4
+
.venv/lib/python3.13/site-packages/annotated_doc-0.0.4.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Sebastián Ramírez
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
13
+ all 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
21
+ THE SOFTWARE.
.venv/lib/python3.13/site-packages/annotated_doc/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .main import Doc as Doc
2
+
3
+ __version__ = "0.0.4"
.venv/lib/python3.13/site-packages/annotated_doc/main.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Doc:
2
+ """Define the documentation of a type annotation using `Annotated`, to be
3
+ used in class attributes, function and method parameters, return values,
4
+ and variables.
5
+
6
+ The value should be a positional-only string literal to allow static tools
7
+ like editors and documentation generators to use it.
8
+
9
+ This complements docstrings.
10
+
11
+ The string value passed is available in the attribute `documentation`.
12
+
13
+ Example:
14
+
15
+ ```Python
16
+ from typing import Annotated
17
+ from annotated_doc import Doc
18
+
19
+ def hi(name: Annotated[str, Doc("Who to say hi to")]) -> None:
20
+ print(f"Hi, {name}!")
21
+ ```
22
+ """
23
+
24
+ def __init__(self, documentation: str, /) -> None:
25
+ self.documentation = documentation
26
+
27
+ def __repr__(self) -> str:
28
+ return f"Doc({self.documentation!r})"
29
+
30
+ def __hash__(self) -> int:
31
+ return hash(self.documentation)
32
+
33
+ def __eq__(self, other: object) -> bool:
34
+ if not isinstance(other, Doc):
35
+ return NotImplemented
36
+ return self.documentation == other.documentation
.venv/lib/python3.13/site-packages/annotated_doc/py.typed ADDED
File without changes
.venv/lib/python3.13/site-packages/annotated_types-0.7.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv/lib/python3.13/site-packages/annotated_types-0.7.0.dist-info/METADATA ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.3
2
+ Name: annotated-types
3
+ Version: 0.7.0
4
+ Summary: Reusable constraint types to use with typing.Annotated
5
+ Project-URL: Homepage, https://github.com/annotated-types/annotated-types
6
+ Project-URL: Source, https://github.com/annotated-types/annotated-types
7
+ Project-URL: Changelog, https://github.com/annotated-types/annotated-types/releases
8
+ Author-email: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, Samuel Colvin <s@muelcolvin.com>, Zac Hatfield-Dodds <zac@zhd.dev>
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Environment :: MacOS X
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Information Technology
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Operating System :: Unix
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.8
27
+ Requires-Dist: typing-extensions>=4.0.0; python_version < '3.9'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # annotated-types
31
+
32
+ [![CI](https://github.com/annotated-types/annotated-types/workflows/CI/badge.svg?event=push)](https://github.com/annotated-types/annotated-types/actions?query=event%3Apush+branch%3Amain+workflow%3ACI)
33
+ [![pypi](https://img.shields.io/pypi/v/annotated-types.svg)](https://pypi.python.org/pypi/annotated-types)
34
+ [![versions](https://img.shields.io/pypi/pyversions/annotated-types.svg)](https://github.com/annotated-types/annotated-types)
35
+ [![license](https://img.shields.io/github/license/annotated-types/annotated-types.svg)](https://github.com/annotated-types/annotated-types/blob/main/LICENSE)
36
+
37
+ [PEP-593](https://peps.python.org/pep-0593/) added `typing.Annotated` as a way of
38
+ adding context-specific metadata to existing types, and specifies that
39
+ `Annotated[T, x]` _should_ be treated as `T` by any tool or library without special
40
+ logic for `x`.
41
+
42
+ This package provides metadata objects which can be used to represent common
43
+ constraints such as upper and lower bounds on scalar values and collection sizes,
44
+ a `Predicate` marker for runtime checks, and
45
+ descriptions of how we intend these metadata to be interpreted. In some cases,
46
+ we also note alternative representations which do not require this package.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install annotated-types
52
+ ```
53
+
54
+ ## Examples
55
+
56
+ ```python
57
+ from typing import Annotated
58
+ from annotated_types import Gt, Len, Predicate
59
+
60
+ class MyClass:
61
+ age: Annotated[int, Gt(18)] # Valid: 19, 20, ...
62
+ # Invalid: 17, 18, "19", 19.0, ...
63
+ factors: list[Annotated[int, Predicate(is_prime)]] # Valid: 2, 3, 5, 7, 11, ...
64
+ # Invalid: 4, 8, -2, 5.0, "prime", ...
65
+
66
+ my_list: Annotated[list[int], Len(0, 10)] # Valid: [], [10, 20, 30, 40, 50]
67
+ # Invalid: (1, 2), ["abc"], [0] * 20
68
+ ```
69
+
70
+ ## Documentation
71
+
72
+ _While `annotated-types` avoids runtime checks for performance, users should not
73
+ construct invalid combinations such as `MultipleOf("non-numeric")` or `Annotated[int, Len(3)]`.
74
+ Downstream implementors may choose to raise an error, emit a warning, silently ignore
75
+ a metadata item, etc., if the metadata objects described below are used with an
76
+ incompatible type - or for any other reason!_
77
+
78
+ ### Gt, Ge, Lt, Le
79
+
80
+ Express inclusive and/or exclusive bounds on orderable values - which may be numbers,
81
+ dates, times, strings, sets, etc. Note that the boundary value need not be of the
82
+ same type that was annotated, so long as they can be compared: `Annotated[int, Gt(1.5)]`
83
+ is fine, for example, and implies that the value is an integer x such that `x > 1.5`.
84
+
85
+ We suggest that implementors may also interpret `functools.partial(operator.le, 1.5)`
86
+ as being equivalent to `Gt(1.5)`, for users who wish to avoid a runtime dependency on
87
+ the `annotated-types` package.
88
+
89
+ To be explicit, these types have the following meanings:
90
+
91
+ * `Gt(x)` - value must be "Greater Than" `x` - equivalent to exclusive minimum
92
+ * `Ge(x)` - value must be "Greater than or Equal" to `x` - equivalent to inclusive minimum
93
+ * `Lt(x)` - value must be "Less Than" `x` - equivalent to exclusive maximum
94
+ * `Le(x)` - value must be "Less than or Equal" to `x` - equivalent to inclusive maximum
95
+
96
+ ### Interval
97
+
98
+ `Interval(gt, ge, lt, le)` allows you to specify an upper and lower bound with a single
99
+ metadata object. `None` attributes should be ignored, and non-`None` attributes
100
+ treated as per the single bounds above.
101
+
102
+ ### MultipleOf
103
+
104
+ `MultipleOf(multiple_of=x)` might be interpreted in two ways:
105
+
106
+ 1. Python semantics, implying `value % multiple_of == 0`, or
107
+ 2. [JSONschema semantics](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.1),
108
+ where `int(value / multiple_of) == value / multiple_of`.
109
+
110
+ We encourage users to be aware of these two common interpretations and their
111
+ distinct behaviours, especially since very large or non-integer numbers make
112
+ it easy to cause silent data corruption due to floating-point imprecision.
113
+
114
+ We encourage libraries to carefully document which interpretation they implement.
115
+
116
+ ### MinLen, MaxLen, Len
117
+
118
+ `Len()` implies that `min_length <= len(value) <= max_length` - lower and upper bounds are inclusive.
119
+
120
+ As well as `Len()` which can optionally include upper and lower bounds, we also
121
+ provide `MinLen(x)` and `MaxLen(y)` which are equivalent to `Len(min_length=x)`
122
+ and `Len(max_length=y)` respectively.
123
+
124
+ `Len`, `MinLen`, and `MaxLen` may be used with any type which supports `len(value)`.
125
+
126
+ Examples of usage:
127
+
128
+ * `Annotated[list, MaxLen(10)]` (or `Annotated[list, Len(max_length=10))`) - list must have a length of 10 or less
129
+ * `Annotated[str, MaxLen(10)]` - string must have a length of 10 or less
130
+ * `Annotated[list, MinLen(3))` (or `Annotated[list, Len(min_length=3))`) - list must have a length of 3 or more
131
+ * `Annotated[list, Len(4, 6)]` - list must have a length of 4, 5, or 6
132
+ * `Annotated[list, Len(8, 8)]` - list must have a length of exactly 8
133
+
134
+ #### Changed in v0.4.0
135
+
136
+ * `min_inclusive` has been renamed to `min_length`, no change in meaning
137
+ * `max_exclusive` has been renamed to `max_length`, upper bound is now **inclusive** instead of **exclusive**
138
+ * The recommendation that slices are interpreted as `Len` has been removed due to ambiguity and different semantic
139
+ meaning of the upper bound in slices vs. `Len`
140
+
141
+ See [issue #23](https://github.com/annotated-types/annotated-types/issues/23) for discussion.
142
+
143
+ ### Timezone
144
+
145
+ `Timezone` can be used with a `datetime` or a `time` to express which timezones
146
+ are allowed. `Annotated[datetime, Timezone(None)]` must be a naive datetime.
147
+ `Timezone[...]` ([literal ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis))
148
+ expresses that any timezone-aware datetime is allowed. You may also pass a specific
149
+ timezone string or [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects)
150
+ object such as `Timezone(timezone.utc)` or `Timezone("Africa/Abidjan")` to express that you only
151
+ allow a specific timezone, though we note that this is often a symptom of fragile design.
152
+
153
+ #### Changed in v0.x.x
154
+
155
+ * `Timezone` accepts [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects) objects instead of
156
+ `timezone`, extending compatibility to [`zoneinfo`](https://docs.python.org/3/library/zoneinfo.html) and third party libraries.
157
+
158
+ ### Unit
159
+
160
+ `Unit(unit: str)` expresses that the annotated numeric value is the magnitude of
161
+ a quantity with the specified unit. For example, `Annotated[float, Unit("m/s")]`
162
+ would be a float representing a velocity in meters per second.
163
+
164
+ Please note that `annotated_types` itself makes no attempt to parse or validate
165
+ the unit string in any way. That is left entirely to downstream libraries,
166
+ such as [`pint`](https://pint.readthedocs.io) or
167
+ [`astropy.units`](https://docs.astropy.org/en/stable/units/).
168
+
169
+ An example of how a library might use this metadata:
170
+
171
+ ```python
172
+ from annotated_types import Unit
173
+ from typing import Annotated, TypeVar, Callable, Any, get_origin, get_args
174
+
175
+ # given a type annotated with a unit:
176
+ Meters = Annotated[float, Unit("m")]
177
+
178
+
179
+ # you can cast the annotation to a specific unit type with any
180
+ # callable that accepts a string and returns the desired type
181
+ T = TypeVar("T")
182
+ def cast_unit(tp: Any, unit_cls: Callable[[str], T]) -> T | None:
183
+ if get_origin(tp) is Annotated:
184
+ for arg in get_args(tp):
185
+ if isinstance(arg, Unit):
186
+ return unit_cls(arg.unit)
187
+ return None
188
+
189
+
190
+ # using `pint`
191
+ import pint
192
+ pint_unit = cast_unit(Meters, pint.Unit)
193
+
194
+
195
+ # using `astropy.units`
196
+ import astropy.units as u
197
+ astropy_unit = cast_unit(Meters, u.Unit)
198
+ ```
199
+
200
+ ### Predicate
201
+
202
+ `Predicate(func: Callable)` expresses that `func(value)` is truthy for valid values.
203
+ Users should prefer the statically inspectable metadata above, but if you need
204
+ the full power and flexibility of arbitrary runtime predicates... here it is.
205
+
206
+ For some common constraints, we provide generic types:
207
+
208
+ * `IsLower = Annotated[T, Predicate(str.islower)]`
209
+ * `IsUpper = Annotated[T, Predicate(str.isupper)]`
210
+ * `IsDigit = Annotated[T, Predicate(str.isdigit)]`
211
+ * `IsFinite = Annotated[T, Predicate(math.isfinite)]`
212
+ * `IsNotFinite = Annotated[T, Predicate(Not(math.isfinite))]`
213
+ * `IsNan = Annotated[T, Predicate(math.isnan)]`
214
+ * `IsNotNan = Annotated[T, Predicate(Not(math.isnan))]`
215
+ * `IsInfinite = Annotated[T, Predicate(math.isinf)]`
216
+ * `IsNotInfinite = Annotated[T, Predicate(Not(math.isinf))]`
217
+
218
+ so that you can write e.g. `x: IsFinite[float] = 2.0` instead of the longer
219
+ (but exactly equivalent) `x: Annotated[float, Predicate(math.isfinite)] = 2.0`.
220
+
221
+ Some libraries might have special logic to handle known or understandable predicates,
222
+ for example by checking for `str.isdigit` and using its presence to both call custom
223
+ logic to enforce digit-only strings, and customise some generated external schema.
224
+ Users are therefore encouraged to avoid indirection like `lambda s: s.lower()`, in
225
+ favor of introspectable methods such as `str.lower` or `re.compile("pattern").search`.
226
+
227
+ To enable basic negation of commonly used predicates like `math.isnan` without introducing introspection that makes it impossible for implementers to introspect the predicate we provide a `Not` wrapper that simply negates the predicate in an introspectable manner. Several of the predicates listed above are created in this manner.
228
+
229
+ We do not specify what behaviour should be expected for predicates that raise
230
+ an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently
231
+ skip invalid constraints, or statically raise an error; or it might try calling it
232
+ and then propagate or discard the resulting
233
+ `TypeError: descriptor 'isdigit' for 'str' objects doesn't apply to a 'int' object`
234
+ exception. We encourage libraries to document the behaviour they choose.
235
+
236
+ ### Doc
237
+
238
+ `doc()` can be used to add documentation information in `Annotated`, for function and method parameters, variables, class attributes, return types, and any place where `Annotated` can be used.
239
+
240
+ It expects a value that can be statically analyzed, as the main use case is for static analysis, editors, documentation generators, and similar tools.
241
+
242
+ It returns a `DocInfo` class with a single attribute `documentation` containing the value passed to `doc()`.
243
+
244
+ This is the early adopter's alternative form of the [`typing-doc` proposal](https://github.com/tiangolo/fastapi/blob/typing-doc/typing_doc.md).
245
+
246
+ ### Integrating downstream types with `GroupedMetadata`
247
+
248
+ Implementers may choose to provide a convenience wrapper that groups multiple pieces of metadata.
249
+ This can help reduce verbosity and cognitive overhead for users.
250
+ For example, an implementer like Pydantic might provide a `Field` or `Meta` type that accepts keyword arguments and transforms these into low-level metadata:
251
+
252
+ ```python
253
+ from dataclasses import dataclass
254
+ from typing import Iterator
255
+ from annotated_types import GroupedMetadata, Ge
256
+
257
+ @dataclass
258
+ class Field(GroupedMetadata):
259
+ ge: int | None = None
260
+ description: str | None = None
261
+
262
+ def __iter__(self) -> Iterator[object]:
263
+ # Iterating over a GroupedMetadata object should yield annotated-types
264
+ # constraint metadata objects which describe it as fully as possible,
265
+ # and may include other unknown objects too.
266
+ if self.ge is not None:
267
+ yield Ge(self.ge)
268
+ if self.description is not None:
269
+ yield Description(self.description)
270
+ ```
271
+
272
+ Libraries consuming annotated-types constraints should check for `GroupedMetadata` and unpack it by iterating over the object and treating the results as if they had been "unpacked" in the `Annotated` type. The same logic should be applied to the [PEP 646 `Unpack` type](https://peps.python.org/pep-0646/), so that `Annotated[T, Field(...)]`, `Annotated[T, Unpack[Field(...)]]` and `Annotated[T, *Field(...)]` are all treated consistently.
273
+
274
+ Libraries consuming annotated-types should also ignore any metadata they do not recongize that came from unpacking a `GroupedMetadata`, just like they ignore unrecognized metadata in `Annotated` itself.
275
+
276
+ Our own `annotated_types.Interval` class is a `GroupedMetadata` which unpacks itself into `Gt`, `Lt`, etc., so this is not an abstract concern. Similarly, `annotated_types.Len` is a `GroupedMetadata` which unpacks itself into `MinLen` (optionally) and `MaxLen`.
277
+
278
+ ### Consuming metadata
279
+
280
+ We intend to not be prescriptive as to _how_ the metadata and constraints are used, but as an example of how one might parse constraints from types annotations see our [implementation in `test_main.py`](https://github.com/annotated-types/annotated-types/blob/f59cf6d1b5255a0fe359b93896759a180bec30ae/tests/test_main.py#L94-L103).
281
+
282
+ It is up to the implementer to determine how this metadata is used.
283
+ You could use the metadata for runtime type checking, for generating schemas or to generate example data, amongst other use cases.
284
+
285
+ ## Design & History
286
+
287
+ This package was designed at the PyCon 2022 sprints by the maintainers of Pydantic
288
+ and Hypothesis, with the goal of making it as easy as possible for end-users to
289
+ provide more informative annotations for use by runtime libraries.
290
+
291
+ It is deliberately minimal, and following PEP-593 allows considerable downstream
292
+ discretion in what (if anything!) they choose to support. Nonetheless, we expect
293
+ that staying simple and covering _only_ the most common use-cases will give users
294
+ and maintainers the best experience we can. If you'd like more constraints for your
295
+ types - follow our lead, by defining them and documenting them downstream!
.venv/lib/python3.13/site-packages/annotated_types-0.7.0.dist-info/RECORD ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ annotated_types-0.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ annotated_types-0.7.0.dist-info/METADATA,sha256=7ltqxksJJ0wCYFGBNIQCWTlWQGeAH0hRFdnK3CB895E,15046
3
+ annotated_types-0.7.0.dist-info/RECORD,,
4
+ annotated_types-0.7.0.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87
5
+ annotated_types-0.7.0.dist-info/licenses/LICENSE,sha256=_hBJiEsaDZNCkB6I4H8ykl0ksxIdmXK2poBfuYJLCV0,1083
6
+ annotated_types/__init__.py,sha256=RynLsRKUEGI0KimXydlD1fZEfEzWwDo0Uon3zOKhG1Q,13819
7
+ annotated_types/__pycache__/__init__.cpython-313.pyc,,
8
+ annotated_types/__pycache__/test_cases.cpython-313.pyc,,
9
+ annotated_types/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ annotated_types/test_cases.py,sha256=zHFX6EpcMbGJ8FzBYDbO56bPwx_DYIVSKbZM-4B3_lg,6421
.venv/lib/python3.13/site-packages/annotated_types-0.7.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.24.2
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.venv/lib/python3.13/site-packages/annotated_types-0.7.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 the 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.13/site-packages/annotated_types/__init__.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+ import types
4
+ from dataclasses import dataclass
5
+ from datetime import tzinfo
6
+ from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, SupportsFloat, SupportsIndex, TypeVar, Union
7
+
8
+ if sys.version_info < (3, 8):
9
+ from typing_extensions import Protocol, runtime_checkable
10
+ else:
11
+ from typing import Protocol, runtime_checkable
12
+
13
+ if sys.version_info < (3, 9):
14
+ from typing_extensions import Annotated, Literal
15
+ else:
16
+ from typing import Annotated, Literal
17
+
18
+ if sys.version_info < (3, 10):
19
+ EllipsisType = type(Ellipsis)
20
+ KW_ONLY = {}
21
+ SLOTS = {}
22
+ else:
23
+ from types import EllipsisType
24
+
25
+ KW_ONLY = {"kw_only": True}
26
+ SLOTS = {"slots": True}
27
+
28
+
29
+ __all__ = (
30
+ 'BaseMetadata',
31
+ 'GroupedMetadata',
32
+ 'Gt',
33
+ 'Ge',
34
+ 'Lt',
35
+ 'Le',
36
+ 'Interval',
37
+ 'MultipleOf',
38
+ 'MinLen',
39
+ 'MaxLen',
40
+ 'Len',
41
+ 'Timezone',
42
+ 'Predicate',
43
+ 'LowerCase',
44
+ 'UpperCase',
45
+ 'IsDigits',
46
+ 'IsFinite',
47
+ 'IsNotFinite',
48
+ 'IsNan',
49
+ 'IsNotNan',
50
+ 'IsInfinite',
51
+ 'IsNotInfinite',
52
+ 'doc',
53
+ 'DocInfo',
54
+ '__version__',
55
+ )
56
+
57
+ __version__ = '0.7.0'
58
+
59
+
60
+ T = TypeVar('T')
61
+
62
+
63
+ # arguments that start with __ are considered
64
+ # positional only
65
+ # see https://peps.python.org/pep-0484/#positional-only-arguments
66
+
67
+
68
+ class SupportsGt(Protocol):
69
+ def __gt__(self: T, __other: T) -> bool:
70
+ ...
71
+
72
+
73
+ class SupportsGe(Protocol):
74
+ def __ge__(self: T, __other: T) -> bool:
75
+ ...
76
+
77
+
78
+ class SupportsLt(Protocol):
79
+ def __lt__(self: T, __other: T) -> bool:
80
+ ...
81
+
82
+
83
+ class SupportsLe(Protocol):
84
+ def __le__(self: T, __other: T) -> bool:
85
+ ...
86
+
87
+
88
+ class SupportsMod(Protocol):
89
+ def __mod__(self: T, __other: T) -> T:
90
+ ...
91
+
92
+
93
+ class SupportsDiv(Protocol):
94
+ def __div__(self: T, __other: T) -> T:
95
+ ...
96
+
97
+
98
+ class BaseMetadata:
99
+ """Base class for all metadata.
100
+
101
+ This exists mainly so that implementers
102
+ can do `isinstance(..., BaseMetadata)` while traversing field annotations.
103
+ """
104
+
105
+ __slots__ = ()
106
+
107
+
108
+ @dataclass(frozen=True, **SLOTS)
109
+ class Gt(BaseMetadata):
110
+ """Gt(gt=x) implies that the value must be greater than x.
111
+
112
+ It can be used with any type that supports the ``>`` operator,
113
+ including numbers, dates and times, strings, sets, and so on.
114
+ """
115
+
116
+ gt: SupportsGt
117
+
118
+
119
+ @dataclass(frozen=True, **SLOTS)
120
+ class Ge(BaseMetadata):
121
+ """Ge(ge=x) implies that the value must be greater than or equal to x.
122
+
123
+ It can be used with any type that supports the ``>=`` operator,
124
+ including numbers, dates and times, strings, sets, and so on.
125
+ """
126
+
127
+ ge: SupportsGe
128
+
129
+
130
+ @dataclass(frozen=True, **SLOTS)
131
+ class Lt(BaseMetadata):
132
+ """Lt(lt=x) implies that the value must be less than x.
133
+
134
+ It can be used with any type that supports the ``<`` operator,
135
+ including numbers, dates and times, strings, sets, and so on.
136
+ """
137
+
138
+ lt: SupportsLt
139
+
140
+
141
+ @dataclass(frozen=True, **SLOTS)
142
+ class Le(BaseMetadata):
143
+ """Le(le=x) implies that the value must be less than or equal to x.
144
+
145
+ It can be used with any type that supports the ``<=`` operator,
146
+ including numbers, dates and times, strings, sets, and so on.
147
+ """
148
+
149
+ le: SupportsLe
150
+
151
+
152
+ @runtime_checkable
153
+ class GroupedMetadata(Protocol):
154
+ """A grouping of multiple objects, like typing.Unpack.
155
+
156
+ `GroupedMetadata` on its own is not metadata and has no meaning.
157
+ All of the constraints and metadata should be fully expressable
158
+ in terms of the `BaseMetadata`'s returned by `GroupedMetadata.__iter__()`.
159
+
160
+ Concrete implementations should override `GroupedMetadata.__iter__()`
161
+ to add their own metadata.
162
+ For example:
163
+
164
+ >>> @dataclass
165
+ >>> class Field(GroupedMetadata):
166
+ >>> gt: float | None = None
167
+ >>> description: str | None = None
168
+ ...
169
+ >>> def __iter__(self) -> Iterable[object]:
170
+ >>> if self.gt is not None:
171
+ >>> yield Gt(self.gt)
172
+ >>> if self.description is not None:
173
+ >>> yield Description(self.gt)
174
+
175
+ Also see the implementation of `Interval` below for an example.
176
+
177
+ Parsers should recognize this and unpack it so that it can be used
178
+ both with and without unpacking:
179
+
180
+ - `Annotated[int, Field(...)]` (parser must unpack Field)
181
+ - `Annotated[int, *Field(...)]` (PEP-646)
182
+ """ # noqa: trailing-whitespace
183
+
184
+ @property
185
+ def __is_annotated_types_grouped_metadata__(self) -> Literal[True]:
186
+ return True
187
+
188
+ def __iter__(self) -> Iterator[object]:
189
+ ...
190
+
191
+ if not TYPE_CHECKING:
192
+ __slots__ = () # allow subclasses to use slots
193
+
194
+ def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None:
195
+ # Basic ABC like functionality without the complexity of an ABC
196
+ super().__init_subclass__(*args, **kwargs)
197
+ if cls.__iter__ is GroupedMetadata.__iter__:
198
+ raise TypeError("Can't subclass GroupedMetadata without implementing __iter__")
199
+
200
+ def __iter__(self) -> Iterator[object]: # noqa: F811
201
+ raise NotImplementedError # more helpful than "None has no attribute..." type errors
202
+
203
+
204
+ @dataclass(frozen=True, **KW_ONLY, **SLOTS)
205
+ class Interval(GroupedMetadata):
206
+ """Interval can express inclusive or exclusive bounds with a single object.
207
+
208
+ It accepts keyword arguments ``gt``, ``ge``, ``lt``, and/or ``le``, which
209
+ are interpreted the same way as the single-bound constraints.
210
+ """
211
+
212
+ gt: Union[SupportsGt, None] = None
213
+ ge: Union[SupportsGe, None] = None
214
+ lt: Union[SupportsLt, None] = None
215
+ le: Union[SupportsLe, None] = None
216
+
217
+ def __iter__(self) -> Iterator[BaseMetadata]:
218
+ """Unpack an Interval into zero or more single-bounds."""
219
+ if self.gt is not None:
220
+ yield Gt(self.gt)
221
+ if self.ge is not None:
222
+ yield Ge(self.ge)
223
+ if self.lt is not None:
224
+ yield Lt(self.lt)
225
+ if self.le is not None:
226
+ yield Le(self.le)
227
+
228
+
229
+ @dataclass(frozen=True, **SLOTS)
230
+ class MultipleOf(BaseMetadata):
231
+ """MultipleOf(multiple_of=x) might be interpreted in two ways:
232
+
233
+ 1. Python semantics, implying ``value % multiple_of == 0``, or
234
+ 2. JSONschema semantics, where ``int(value / multiple_of) == value / multiple_of``
235
+
236
+ We encourage users to be aware of these two common interpretations,
237
+ and libraries to carefully document which they implement.
238
+ """
239
+
240
+ multiple_of: Union[SupportsDiv, SupportsMod]
241
+
242
+
243
+ @dataclass(frozen=True, **SLOTS)
244
+ class MinLen(BaseMetadata):
245
+ """
246
+ MinLen() implies minimum inclusive length,
247
+ e.g. ``len(value) >= min_length``.
248
+ """
249
+
250
+ min_length: Annotated[int, Ge(0)]
251
+
252
+
253
+ @dataclass(frozen=True, **SLOTS)
254
+ class MaxLen(BaseMetadata):
255
+ """
256
+ MaxLen() implies maximum inclusive length,
257
+ e.g. ``len(value) <= max_length``.
258
+ """
259
+
260
+ max_length: Annotated[int, Ge(0)]
261
+
262
+
263
+ @dataclass(frozen=True, **SLOTS)
264
+ class Len(GroupedMetadata):
265
+ """
266
+ Len() implies that ``min_length <= len(value) <= max_length``.
267
+
268
+ Upper bound may be omitted or ``None`` to indicate no upper length bound.
269
+ """
270
+
271
+ min_length: Annotated[int, Ge(0)] = 0
272
+ max_length: Optional[Annotated[int, Ge(0)]] = None
273
+
274
+ def __iter__(self) -> Iterator[BaseMetadata]:
275
+ """Unpack a Len into zone or more single-bounds."""
276
+ if self.min_length > 0:
277
+ yield MinLen(self.min_length)
278
+ if self.max_length is not None:
279
+ yield MaxLen(self.max_length)
280
+
281
+
282
+ @dataclass(frozen=True, **SLOTS)
283
+ class Timezone(BaseMetadata):
284
+ """Timezone(tz=...) requires a datetime to be aware (or ``tz=None``, naive).
285
+
286
+ ``Annotated[datetime, Timezone(None)]`` must be a naive datetime.
287
+ ``Timezone[...]`` (the ellipsis literal) expresses that the datetime must be
288
+ tz-aware but any timezone is allowed.
289
+
290
+ You may also pass a specific timezone string or tzinfo object such as
291
+ ``Timezone(timezone.utc)`` or ``Timezone("Africa/Abidjan")`` to express that
292
+ you only allow a specific timezone, though we note that this is often
293
+ a symptom of poor design.
294
+ """
295
+
296
+ tz: Union[str, tzinfo, EllipsisType, None]
297
+
298
+
299
+ @dataclass(frozen=True, **SLOTS)
300
+ class Unit(BaseMetadata):
301
+ """Indicates that the value is a physical quantity with the specified unit.
302
+
303
+ It is intended for usage with numeric types, where the value represents the
304
+ magnitude of the quantity. For example, ``distance: Annotated[float, Unit('m')]``
305
+ or ``speed: Annotated[float, Unit('m/s')]``.
306
+
307
+ Interpretation of the unit string is left to the discretion of the consumer.
308
+ It is suggested to follow conventions established by python libraries that work
309
+ with physical quantities, such as
310
+
311
+ - ``pint`` : <https://pint.readthedocs.io/en/stable/>
312
+ - ``astropy.units``: <https://docs.astropy.org/en/stable/units/>
313
+
314
+ For indicating a quantity with a certain dimensionality but without a specific unit
315
+ it is recommended to use square brackets, e.g. `Annotated[float, Unit('[time]')]`.
316
+ Note, however, ``annotated_types`` itself makes no use of the unit string.
317
+ """
318
+
319
+ unit: str
320
+
321
+
322
+ @dataclass(frozen=True, **SLOTS)
323
+ class Predicate(BaseMetadata):
324
+ """``Predicate(func: Callable)`` implies `func(value)` is truthy for valid values.
325
+
326
+ Users should prefer statically inspectable metadata, but if you need the full
327
+ power and flexibility of arbitrary runtime predicates... here it is.
328
+
329
+ We provide a few predefined predicates for common string constraints:
330
+ ``IsLower = Predicate(str.islower)``, ``IsUpper = Predicate(str.isupper)``, and
331
+ ``IsDigits = Predicate(str.isdigit)``. Users are encouraged to use methods which
332
+ can be given special handling, and avoid indirection like ``lambda s: s.lower()``.
333
+
334
+ Some libraries might have special logic to handle certain predicates, e.g. by
335
+ checking for `str.isdigit` and using its presence to both call custom logic to
336
+ enforce digit-only strings, and customise some generated external schema.
337
+
338
+ We do not specify what behaviour should be expected for predicates that raise
339
+ an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently
340
+ skip invalid constraints, or statically raise an error; or it might try calling it
341
+ and then propagate or discard the resulting exception.
342
+ """
343
+
344
+ func: Callable[[Any], bool]
345
+
346
+ def __repr__(self) -> str:
347
+ if getattr(self.func, "__name__", "<lambda>") == "<lambda>":
348
+ return f"{self.__class__.__name__}({self.func!r})"
349
+ if isinstance(self.func, (types.MethodType, types.BuiltinMethodType)) and (
350
+ namespace := getattr(self.func.__self__, "__name__", None)
351
+ ):
352
+ return f"{self.__class__.__name__}({namespace}.{self.func.__name__})"
353
+ if isinstance(self.func, type(str.isascii)): # method descriptor
354
+ return f"{self.__class__.__name__}({self.func.__qualname__})"
355
+ return f"{self.__class__.__name__}({self.func.__name__})"
356
+
357
+
358
+ @dataclass
359
+ class Not:
360
+ func: Callable[[Any], bool]
361
+
362
+ def __call__(self, __v: Any) -> bool:
363
+ return not self.func(__v)
364
+
365
+
366
+ _StrType = TypeVar("_StrType", bound=str)
367
+
368
+ LowerCase = Annotated[_StrType, Predicate(str.islower)]
369
+ """
370
+ Return True if the string is a lowercase string, False otherwise.
371
+
372
+ A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
373
+ """ # noqa: E501
374
+ UpperCase = Annotated[_StrType, Predicate(str.isupper)]
375
+ """
376
+ Return True if the string is an uppercase string, False otherwise.
377
+
378
+ A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
379
+ """ # noqa: E501
380
+ IsDigit = Annotated[_StrType, Predicate(str.isdigit)]
381
+ IsDigits = IsDigit # type: ignore # plural for backwards compatibility, see #63
382
+ """
383
+ Return True if the string is a digit string, False otherwise.
384
+
385
+ A string is a digit string if all characters in the string are digits and there is at least one character in the string.
386
+ """ # noqa: E501
387
+ IsAscii = Annotated[_StrType, Predicate(str.isascii)]
388
+ """
389
+ Return True if all characters in the string are ASCII, False otherwise.
390
+
391
+ ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
392
+ """
393
+
394
+ _NumericType = TypeVar('_NumericType', bound=Union[SupportsFloat, SupportsIndex])
395
+ IsFinite = Annotated[_NumericType, Predicate(math.isfinite)]
396
+ """Return True if x is neither an infinity nor a NaN, and False otherwise."""
397
+ IsNotFinite = Annotated[_NumericType, Predicate(Not(math.isfinite))]
398
+ """Return True if x is one of infinity or NaN, and False otherwise"""
399
+ IsNan = Annotated[_NumericType, Predicate(math.isnan)]
400
+ """Return True if x is a NaN (not a number), and False otherwise."""
401
+ IsNotNan = Annotated[_NumericType, Predicate(Not(math.isnan))]
402
+ """Return True if x is anything but NaN (not a number), and False otherwise."""
403
+ IsInfinite = Annotated[_NumericType, Predicate(math.isinf)]
404
+ """Return True if x is a positive or negative infinity, and False otherwise."""
405
+ IsNotInfinite = Annotated[_NumericType, Predicate(Not(math.isinf))]
406
+ """Return True if x is neither a positive or negative infinity, and False otherwise."""
407
+
408
+ try:
409
+ from typing_extensions import DocInfo, doc # type: ignore [attr-defined]
410
+ except ImportError:
411
+
412
+ @dataclass(frozen=True, **SLOTS)
413
+ class DocInfo: # type: ignore [no-redef]
414
+ """ "
415
+ The return value of doc(), mainly to be used by tools that want to extract the
416
+ Annotated documentation at runtime.
417
+ """
418
+
419
+ documentation: str
420
+ """The documentation string passed to doc()."""
421
+
422
+ def doc(
423
+ documentation: str,
424
+ ) -> DocInfo:
425
+ """
426
+ Add documentation to a type annotation inside of Annotated.
427
+
428
+ For example:
429
+
430
+ >>> def hi(name: Annotated[int, doc("The name of the user")]) -> None: ...
431
+ """
432
+ return DocInfo(documentation)
.venv/lib/python3.13/site-packages/annotated_types/py.typed ADDED
File without changes
.venv/lib/python3.13/site-packages/annotated_types/test_cases.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+ from datetime import date, datetime, timedelta, timezone
4
+ from decimal import Decimal
5
+ from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Set, Tuple
6
+
7
+ if sys.version_info < (3, 9):
8
+ from typing_extensions import Annotated
9
+ else:
10
+ from typing import Annotated
11
+
12
+ import annotated_types as at
13
+
14
+
15
+ class Case(NamedTuple):
16
+ """
17
+ A test case for `annotated_types`.
18
+ """
19
+
20
+ annotation: Any
21
+ valid_cases: Iterable[Any]
22
+ invalid_cases: Iterable[Any]
23
+
24
+
25
+ def cases() -> Iterable[Case]:
26
+ # Gt, Ge, Lt, Le
27
+ yield Case(Annotated[int, at.Gt(4)], (5, 6, 1000), (4, 0, -1))
28
+ yield Case(Annotated[float, at.Gt(0.5)], (0.6, 0.7, 0.8, 0.9), (0.5, 0.0, -0.1))
29
+ yield Case(
30
+ Annotated[datetime, at.Gt(datetime(2000, 1, 1))],
31
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
32
+ [datetime(2000, 1, 1), datetime(1999, 12, 31)],
33
+ )
34
+ yield Case(
35
+ Annotated[datetime, at.Gt(date(2000, 1, 1))],
36
+ [date(2000, 1, 2), date(2000, 1, 3)],
37
+ [date(2000, 1, 1), date(1999, 12, 31)],
38
+ )
39
+ yield Case(
40
+ Annotated[datetime, at.Gt(Decimal('1.123'))],
41
+ [Decimal('1.1231'), Decimal('123')],
42
+ [Decimal('1.123'), Decimal('0')],
43
+ )
44
+
45
+ yield Case(Annotated[int, at.Ge(4)], (4, 5, 6, 1000, 4), (0, -1))
46
+ yield Case(Annotated[float, at.Ge(0.5)], (0.5, 0.6, 0.7, 0.8, 0.9), (0.4, 0.0, -0.1))
47
+ yield Case(
48
+ Annotated[datetime, at.Ge(datetime(2000, 1, 1))],
49
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
50
+ [datetime(1998, 1, 1), datetime(1999, 12, 31)],
51
+ )
52
+
53
+ yield Case(Annotated[int, at.Lt(4)], (0, -1), (4, 5, 6, 1000, 4))
54
+ yield Case(Annotated[float, at.Lt(0.5)], (0.4, 0.0, -0.1), (0.5, 0.6, 0.7, 0.8, 0.9))
55
+ yield Case(
56
+ Annotated[datetime, at.Lt(datetime(2000, 1, 1))],
57
+ [datetime(1999, 12, 31), datetime(1999, 12, 31)],
58
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
59
+ )
60
+
61
+ yield Case(Annotated[int, at.Le(4)], (4, 0, -1), (5, 6, 1000))
62
+ yield Case(Annotated[float, at.Le(0.5)], (0.5, 0.0, -0.1), (0.6, 0.7, 0.8, 0.9))
63
+ yield Case(
64
+ Annotated[datetime, at.Le(datetime(2000, 1, 1))],
65
+ [datetime(2000, 1, 1), datetime(1999, 12, 31)],
66
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
67
+ )
68
+
69
+ # Interval
70
+ yield Case(Annotated[int, at.Interval(gt=4)], (5, 6, 1000), (4, 0, -1))
71
+ yield Case(Annotated[int, at.Interval(gt=4, lt=10)], (5, 6), (4, 10, 1000, 0, -1))
72
+ yield Case(Annotated[float, at.Interval(ge=0.5, le=1)], (0.5, 0.9, 1), (0.49, 1.1))
73
+ yield Case(
74
+ Annotated[datetime, at.Interval(gt=datetime(2000, 1, 1), le=datetime(2000, 1, 3))],
75
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
76
+ [datetime(2000, 1, 1), datetime(2000, 1, 4)],
77
+ )
78
+
79
+ yield Case(Annotated[int, at.MultipleOf(multiple_of=3)], (0, 3, 9), (1, 2, 4))
80
+ yield Case(Annotated[float, at.MultipleOf(multiple_of=0.5)], (0, 0.5, 1, 1.5), (0.4, 1.1))
81
+
82
+ # lengths
83
+
84
+ yield Case(Annotated[str, at.MinLen(3)], ('123', '1234', 'x' * 10), ('', '1', '12'))
85
+ yield Case(Annotated[str, at.Len(3)], ('123', '1234', 'x' * 10), ('', '1', '12'))
86
+ yield Case(Annotated[List[int], at.MinLen(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2]))
87
+ yield Case(Annotated[List[int], at.Len(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2]))
88
+
89
+ yield Case(Annotated[str, at.MaxLen(4)], ('', '1234'), ('12345', 'x' * 10))
90
+ yield Case(Annotated[str, at.Len(0, 4)], ('', '1234'), ('12345', 'x' * 10))
91
+ yield Case(Annotated[List[str], at.MaxLen(4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10))
92
+ yield Case(Annotated[List[str], at.Len(0, 4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10))
93
+
94
+ yield Case(Annotated[str, at.Len(3, 5)], ('123', '12345'), ('', '1', '12', '123456', 'x' * 10))
95
+ yield Case(Annotated[str, at.Len(3, 3)], ('123',), ('12', '1234'))
96
+
97
+ yield Case(Annotated[Dict[int, int], at.Len(2, 3)], [{1: 1, 2: 2}], [{}, {1: 1}, {1: 1, 2: 2, 3: 3, 4: 4}])
98
+ yield Case(Annotated[Set[int], at.Len(2, 3)], ({1, 2}, {1, 2, 3}), (set(), {1}, {1, 2, 3, 4}))
99
+ yield Case(Annotated[Tuple[int, ...], at.Len(2, 3)], ((1, 2), (1, 2, 3)), ((), (1,), (1, 2, 3, 4)))
100
+
101
+ # Timezone
102
+
103
+ yield Case(
104
+ Annotated[datetime, at.Timezone(None)], [datetime(2000, 1, 1)], [datetime(2000, 1, 1, tzinfo=timezone.utc)]
105
+ )
106
+ yield Case(
107
+ Annotated[datetime, at.Timezone(...)], [datetime(2000, 1, 1, tzinfo=timezone.utc)], [datetime(2000, 1, 1)]
108
+ )
109
+ yield Case(
110
+ Annotated[datetime, at.Timezone(timezone.utc)],
111
+ [datetime(2000, 1, 1, tzinfo=timezone.utc)],
112
+ [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))],
113
+ )
114
+ yield Case(
115
+ Annotated[datetime, at.Timezone('Europe/London')],
116
+ [datetime(2000, 1, 1, tzinfo=timezone(timedelta(0), name='Europe/London'))],
117
+ [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))],
118
+ )
119
+
120
+ # Quantity
121
+
122
+ yield Case(Annotated[float, at.Unit(unit='m')], (5, 4.2), ('5m', '4.2m'))
123
+
124
+ # predicate types
125
+
126
+ yield Case(at.LowerCase[str], ['abc', 'foobar'], ['', 'A', 'Boom'])
127
+ yield Case(at.UpperCase[str], ['ABC', 'DEFO'], ['', 'a', 'abc', 'AbC'])
128
+ yield Case(at.IsDigit[str], ['123'], ['', 'ab', 'a1b2'])
129
+ yield Case(at.IsAscii[str], ['123', 'foo bar'], ['£100', '😊', 'whatever 👀'])
130
+
131
+ yield Case(Annotated[int, at.Predicate(lambda x: x % 2 == 0)], [0, 2, 4], [1, 3, 5])
132
+
133
+ yield Case(at.IsFinite[float], [1.23], [math.nan, math.inf, -math.inf])
134
+ yield Case(at.IsNotFinite[float], [math.nan, math.inf], [1.23])
135
+ yield Case(at.IsNan[float], [math.nan], [1.23, math.inf])
136
+ yield Case(at.IsNotNan[float], [1.23, math.inf], [math.nan])
137
+ yield Case(at.IsInfinite[float], [math.inf], [math.nan, 1.23])
138
+ yield Case(at.IsNotInfinite[float], [math.nan, 1.23], [math.inf])
139
+
140
+ # check stacked predicates
141
+ yield Case(at.IsInfinite[Annotated[float, at.Predicate(lambda x: x > 0)]], [math.inf], [-math.inf, 1.23, math.nan])
142
+
143
+ # doc
144
+ yield Case(Annotated[int, at.doc("A number")], [1, 2], [])
145
+
146
+ # custom GroupedMetadata
147
+ class MyCustomGroupedMetadata(at.GroupedMetadata):
148
+ def __iter__(self) -> Iterator[at.Predicate]:
149
+ yield at.Predicate(lambda x: float(x).is_integer())
150
+
151
+ yield Case(Annotated[float, MyCustomGroupedMetadata()], [0, 2.0], [0.01, 1.5])
.venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/METADATA ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: anyio
3
+ Version: 4.14.2
4
+ Summary: High-level concurrency and networking framework on top of asyncio or Trio
5
+ Author-email: Alex Grönholm <alex.gronholm@nextday.fi>
6
+ License-Expression: MIT
7
+ Project-URL: Documentation, https://anyio.readthedocs.io/en/latest/
8
+ Project-URL: Changelog, https://anyio.readthedocs.io/en/stable/versionhistory.html
9
+ Project-URL: Source code, https://github.com/agronholm/anyio
10
+ Project-URL: Issue tracker, https://github.com/agronholm/anyio/issues
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Framework :: AnyIO
14
+ Classifier: Typing :: Typed
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/x-rst
25
+ License-File: LICENSE
26
+ Requires-Dist: exceptiongroup>=1.0.2; python_version < "3.11"
27
+ Requires-Dist: idna>=2.8
28
+ Requires-Dist: typing_extensions>=4.5; python_version < "3.13"
29
+ Provides-Extra: trio
30
+ Requires-Dist: trio>=0.32.0; extra == "trio"
31
+ Dynamic: license-file
32
+
33
+ .. image:: https://github.com/agronholm/anyio/actions/workflows/test.yml/badge.svg
34
+ :target: https://github.com/agronholm/anyio/actions/workflows/test.yml
35
+ :alt: Build Status
36
+ .. image:: https://coveralls.io/repos/github/agronholm/anyio/badge.svg?branch=master
37
+ :target: https://coveralls.io/github/agronholm/anyio?branch=master
38
+ :alt: Code Coverage
39
+ .. image:: https://readthedocs.org/projects/anyio/badge/?version=latest
40
+ :target: https://anyio.readthedocs.io/en/latest/?badge=latest
41
+ :alt: Documentation
42
+ .. image:: https://badges.gitter.im/gitterHQ/gitter.svg
43
+ :target: https://gitter.im/python-trio/AnyIO
44
+ :alt: Gitter chat
45
+ .. image:: https://tidelift.com/badges/package/pypi/anyio
46
+ :target: https://tidelift.com/subscription/pkg/pypi-anyio
47
+ :alt: Tidelift
48
+
49
+ AnyIO is an asynchronous networking and concurrency library that works on top of either asyncio_ or
50
+ Trio_. It implements Trio-like `structured concurrency`_ (SC) on top of asyncio and works in harmony
51
+ with the native SC of Trio itself.
52
+
53
+ Applications and libraries written against AnyIO's API will run unmodified on either asyncio_ or
54
+ Trio_. AnyIO can also be adopted into a library or application incrementally – bit by bit, no full
55
+ refactoring necessary. It will blend in with the native libraries of your chosen backend.
56
+
57
+ To find out why you might want to use AnyIO's APIs instead of asyncio's, you can read about it
58
+ `here <https://anyio.readthedocs.io/en/stable/why.html>`_.
59
+
60
+ Documentation
61
+ -------------
62
+
63
+ View full documentation at: https://anyio.readthedocs.io/
64
+
65
+ Features
66
+ --------
67
+
68
+ AnyIO offers the following functionality:
69
+
70
+ * Task groups (nurseries_ in trio terminology)
71
+ * High-level networking (TCP, UDP and UNIX sockets)
72
+
73
+ * `Happy eyeballs`_ algorithm for TCP connections (more robust than that of asyncio on Python
74
+ 3.8)
75
+ * async/await style UDP sockets (unlike asyncio where you still have to use Transports and
76
+ Protocols)
77
+
78
+ * A versatile API for byte streams and object streams
79
+ * Inter-task synchronization and communication (locks, conditions, events, semaphores, object
80
+ streams)
81
+ * Worker threads
82
+ * Subprocesses
83
+ * Subinterpreter support for code parallelization (on Python 3.13 and later)
84
+ * Asynchronous file I/O (using worker threads)
85
+ * Signal handling
86
+ * Asynchronous versions of the functools_ and itertools_ modules
87
+
88
+ AnyIO also comes with its own pytest_ plugin which also supports asynchronous fixtures.
89
+ It even works with the popular Hypothesis_ library.
90
+
91
+ .. _asyncio: https://docs.python.org/3/library/asyncio.html
92
+ .. _Trio: https://github.com/python-trio/trio
93
+ .. _structured concurrency: https://en.wikipedia.org/wiki/Structured_concurrency
94
+ .. _nurseries: https://trio.readthedocs.io/en/stable/reference-core.html#nurseries-and-spawning
95
+ .. _Happy eyeballs: https://en.wikipedia.org/wiki/Happy_Eyeballs
96
+ .. _pytest: https://docs.pytest.org/en/latest/
97
+ .. _functools: https://docs.python.org/3/library/functools.html
98
+ .. _itertools: https://docs.python.org/3/library/itertools.html
99
+ .. _Hypothesis: https://hypothesis.works/
100
+
101
+ Security contact information
102
+ ----------------------------
103
+
104
+ To report a security vulnerability, please use the `Tidelift security contact`_.
105
+ Tidelift will coordinate the fix and disclosure.
106
+
107
+ .. _Tidelift security contact: https://tidelift.com/security
.venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/RECORD ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ anyio-4.14.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ anyio-4.14.2.dist-info/METADATA,sha256=xeb8Tf2DMxmROyh756MNmTXpIIx--RdjBiGFWqrE1Bk,4645
3
+ anyio-4.14.2.dist-info/RECORD,,
4
+ anyio-4.14.2.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
5
+ anyio-4.14.2.dist-info/entry_points.txt,sha256=_d6Yu6uiaZmNe0CydowirE9Cmg7zUL2g08tQpoS3Qvc,39
6
+ anyio-4.14.2.dist-info/licenses/LICENSE,sha256=U2GsncWPLvX9LpsJxoKXwX8ElQkJu8gCO9uC6s8iwrA,1081
7
+ anyio-4.14.2.dist-info/scm_file_list.json,sha256=wDSXGv8Ehn5ZW5BhB-RlaAc16zY_OfO27qrlMfMMZy8,3654
8
+ anyio-4.14.2.dist-info/scm_version.json,sha256=KgaUx31SyaqGFQFKpG3FO9kCk-ygOKS7Uf0yk56OzaY,161
9
+ anyio-4.14.2.dist-info/top_level.txt,sha256=QglSMiWX8_5dpoVAEIHdEYzvqFMdSYWmCj6tYw2ITkQ,6
10
+ anyio/__init__.py,sha256=HitUIfzvAojSeaHVmJ9rFn8k_yI63G6s_jUL2QChf4U,6405
11
+ anyio/__pycache__/__init__.cpython-313.pyc,,
12
+ anyio/__pycache__/from_thread.cpython-313.pyc,,
13
+ anyio/__pycache__/functools.cpython-313.pyc,,
14
+ anyio/__pycache__/itertools.cpython-313.pyc,,
15
+ anyio/__pycache__/lowlevel.cpython-313.pyc,,
16
+ anyio/__pycache__/pytest_plugin.cpython-313.pyc,,
17
+ anyio/__pycache__/to_interpreter.cpython-313.pyc,,
18
+ anyio/__pycache__/to_process.cpython-313.pyc,,
19
+ anyio/__pycache__/to_thread.cpython-313.pyc,,
20
+ anyio/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
+ anyio/_backends/__pycache__/__init__.cpython-313.pyc,,
22
+ anyio/_backends/__pycache__/_asyncio.cpython-313.pyc,,
23
+ anyio/_backends/__pycache__/_trio.cpython-313.pyc,,
24
+ anyio/_backends/_asyncio.py,sha256=eK0j8PI0O7y3bX8cUBsafoWP8wsXR-szP6ciyP4Mkkk,104400
25
+ anyio/_backends/_trio.py,sha256=hoTXL8zI81v4UE-YT_cr2fzh_zY1mKdmZD3oQHmeR0E,45583
26
+ anyio/_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
27
+ anyio/_core/__pycache__/__init__.cpython-313.pyc,,
28
+ anyio/_core/__pycache__/_asyncio_selector_thread.cpython-313.pyc,,
29
+ anyio/_core/__pycache__/_contextmanagers.cpython-313.pyc,,
30
+ anyio/_core/__pycache__/_eventloop.cpython-313.pyc,,
31
+ anyio/_core/__pycache__/_exceptions.cpython-313.pyc,,
32
+ anyio/_core/__pycache__/_fileio.cpython-313.pyc,,
33
+ anyio/_core/__pycache__/_resources.cpython-313.pyc,,
34
+ anyio/_core/__pycache__/_signals.cpython-313.pyc,,
35
+ anyio/_core/__pycache__/_sockets.cpython-313.pyc,,
36
+ anyio/_core/__pycache__/_streams.cpython-313.pyc,,
37
+ anyio/_core/__pycache__/_subprocesses.cpython-313.pyc,,
38
+ anyio/_core/__pycache__/_synchronization.cpython-313.pyc,,
39
+ anyio/_core/__pycache__/_tasks.cpython-313.pyc,,
40
+ anyio/_core/__pycache__/_tempfile.cpython-313.pyc,,
41
+ anyio/_core/__pycache__/_testing.cpython-313.pyc,,
42
+ anyio/_core/__pycache__/_typedattr.cpython-313.pyc,,
43
+ anyio/_core/_asyncio_selector_thread.py,sha256=2PdxFM3cs02Kp6BSppbvmRT7q7asreTW5FgBxEsflBo,5626
44
+ anyio/_core/_contextmanagers.py,sha256=YInBCabiEeS-UaP_Jdxa1CaFC71ETPW8HZTHIM8Rsc8,7215
45
+ anyio/_core/_eventloop.py,sha256=ByZUeJD9alMfcyTseRo5IzTO0IltEul_Gyq9iqSjqDk,6658
46
+ anyio/_core/_exceptions.py,sha256=OfzLO4Z3Hog1TnipbIn72YNtkoYxS4lHW9MqKDeGc88,4936
47
+ anyio/_core/_fileio.py,sha256=hHfyV0bXDL-R2ZNnInwse3nmTAd36AIz1cBxgmAwzAQ,31358
48
+ anyio/_core/_resources.py,sha256=NbmU5O5UX3xEyACnkmYX28Fmwdl-f-ny0tHym26e0w0,435
49
+ anyio/_core/_signals.py,sha256=mjTBB2hTKNPRlU0IhnijeQedpWOGERDiMjSlJQsFrug,1016
50
+ anyio/_core/_sockets.py,sha256=HtjiSH-yzehlqh_LpD3PGIafDuUCwd8gueUuk5MFeNk,35288
51
+ anyio/_core/_streams.py,sha256=FczFwIgDpnkK0bODWJXMpsUJYdvAD04kaUaGzJU8DK0,1806
52
+ anyio/_core/_subprocesses.py,sha256=M2GCc4NKXCbB_GtEskJgndiM2b0VS0NK_ohmFxri7O8,7923
53
+ anyio/_core/_synchronization.py,sha256=kgPk88-eVOmY-pDNs-ReRbcEelY1a7YczuVBPsZwc8A,21591
54
+ anyio/_core/_tasks.py,sha256=y99vRi-AFzEv6kyvIwqrzuskE2NMiNItWnuWGk7eOr4,13126
55
+ anyio/_core/_tempfile.py,sha256=jE2w59FRF3yRo4vjkjfZF2YcqsBZvc66VWRwrJGDYGk,19624
56
+ anyio/_core/_testing.py,sha256=u7MPqGXwpTxqI7hclSdNA30z2GH1Nw258uwKvy_RfBg,2340
57
+ anyio/_core/_typedattr.py,sha256=P4ozZikn3-DbpoYcvyghS_FOYAgbmUxeoU8-L_07pZM,2508
58
+ anyio/abc/__init__.py,sha256=6mWhcl_pGXhrgZVHP_TCfMvIXIOp9mroEFM90fYCU_U,2869
59
+ anyio/abc/__pycache__/__init__.cpython-313.pyc,,
60
+ anyio/abc/__pycache__/_eventloop.cpython-313.pyc,,
61
+ anyio/abc/__pycache__/_resources.cpython-313.pyc,,
62
+ anyio/abc/__pycache__/_sockets.cpython-313.pyc,,
63
+ anyio/abc/__pycache__/_streams.cpython-313.pyc,,
64
+ anyio/abc/__pycache__/_subprocesses.cpython-313.pyc,,
65
+ anyio/abc/__pycache__/_tasks.cpython-313.pyc,,
66
+ anyio/abc/__pycache__/_testing.cpython-313.pyc,,
67
+ anyio/abc/_eventloop.py,sha256=OqWYSEj0TmwL_xniCJt3_jHFWsuMk9THk8tCTGsKapI,10681
68
+ anyio/abc/_resources.py,sha256=DrYvkNN1hH6Uvv5_5uKySvDsnknGVDe8FCKfko0VtN8,783
69
+ anyio/abc/_sockets.py,sha256=OmVDrfemVvF9c5K1tpBgQyV6fn5v0XyCExLAqBOGz9o,13124
70
+ anyio/abc/_streams.py,sha256=rnSwRy-6y80TPQtIXit5LjMMiU1CCWS1oMNsmJQHRTg,7582
71
+ anyio/abc/_subprocesses.py,sha256=cumAPJTktOQtw63IqG0lDpyZqu_l1EElvQHMiwJgL08,2067
72
+ anyio/abc/_tasks.py,sha256=m-FtE4phxeNIELSG7A3H7VUz3jA2Ib5J2JIew8-PS6o,6642
73
+ anyio/abc/_testing.py,sha256=9YYM2AXsYFvf4PLjUEr6yRxDiUeB5QbY_gOg0X_C6lY,2034
74
+ anyio/from_thread.py,sha256=JYsbaCaIB_Iit6kNhtXSteJGt4PcQ7ncq0nIpcelIrg,19265
75
+ anyio/functools.py,sha256=T4JS8IXq-x1S0Lbo2owF8l9fza2KypO147QLeyz4cjs,11797
76
+ anyio/itertools.py,sha256=QV-9mnRCr2yBph8g01QFvN-bQ_Yle-8Sl13YSydBlMI,16168
77
+ anyio/lowlevel.py,sha256=-59484Z6K5jF7XJJhHxYHIKnvFH_uAeMhl9a_AfaSHI,6280
78
+ anyio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
79
+ anyio/pytest_plugin.py,sha256=paMpI_VMNQf2bir0LfvgMpXSiYJoHDzWdKUVTyoHmvQ,13609
80
+ anyio/streams/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
81
+ anyio/streams/__pycache__/__init__.cpython-313.pyc,,
82
+ anyio/streams/__pycache__/buffered.cpython-313.pyc,,
83
+ anyio/streams/__pycache__/file.cpython-313.pyc,,
84
+ anyio/streams/__pycache__/memory.cpython-313.pyc,,
85
+ anyio/streams/__pycache__/stapled.cpython-313.pyc,,
86
+ anyio/streams/__pycache__/text.cpython-313.pyc,,
87
+ anyio/streams/__pycache__/tls.cpython-313.pyc,,
88
+ anyio/streams/buffered.py,sha256=u7hCD8SNrYHcutG6K5wEiy1F88-pizgjvEFM22Kq2Cw,6746
89
+ anyio/streams/file.py,sha256=6jujI2m-QJITqqKFamrupX_DNsU7y2Fz3omLZxOLuY0,4524
90
+ anyio/streams/memory.py,sha256=ZmKWCLpyItOCXmvCQT-L8IyJHNFaB-OVJbrn88CaMo0,10776
91
+ anyio/streams/stapled.py,sha256=mDNF9Gj4deXfOuKSZmgkEG-QExYAKAGjYBHbrs-rJaQ,4486
92
+ anyio/streams/text.py,sha256=BcVAGJw1VRvtIqnv-o0Rb0pwH7p8vwlvl21xHq522ag,5765
93
+ anyio/streams/tls.py,sha256=Gvs--YOoFxcyn-hakXOiPM8H-aEp8nsU6k9rTrKqJA4,15801
94
+ anyio/to_interpreter.py,sha256=_mLngrMy97TMR6VbW4Y6YzDUk9ZuPcQMPlkuyRh3C9k,7100
95
+ anyio/to_process.py,sha256=jHw7v6XHBNIfYa6DqnqKY0gsRo8ScOCh8fo19fqFvjU,9848
96
+ anyio/to_thread.py,sha256=bYszW0lCDfTmLnXbAYic05HEe_Di_0UWKabgL2vU0T0,2750
.venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
.venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [pytest11]
2
+ anyio = anyio.pytest_plugin
.venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Alex Grönholm
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ 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, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
.venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/scm_file_list.json ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "files": [
3
+ ".pre-commit-config.yaml",
4
+ "LICENSE",
5
+ "pyproject.toml",
6
+ "AGENTS.md",
7
+ "README.rst",
8
+ "CLAUDE.md",
9
+ ".readthedocs.yml",
10
+ ".gitignore",
11
+ "docs/tempfile.rst",
12
+ "docs/signals.rst",
13
+ "docs/synchronization.rst",
14
+ "docs/contextmanagers.rst",
15
+ "docs/testing.rst",
16
+ "docs/networking.rst",
17
+ "docs/contributing.rst",
18
+ "docs/index.rst",
19
+ "docs/versionhistory.rst",
20
+ "docs/threads.rst",
21
+ "docs/api.rst",
22
+ "docs/typedattrs.rst",
23
+ "docs/basics.rst",
24
+ "docs/fileio.rst",
25
+ "docs/cancellation.rst",
26
+ "docs/support.rst",
27
+ "docs/streams.rst",
28
+ "docs/why.rst",
29
+ "docs/tasks.rst",
30
+ "docs/migration.rst",
31
+ "docs/conf.py",
32
+ "docs/subprocesses.rst",
33
+ "docs/faq.rst",
34
+ "docs/subinterpreters.rst",
35
+ "src/anyio/functools.py",
36
+ "src/anyio/py.typed",
37
+ "src/anyio/__init__.py",
38
+ "src/anyio/pytest_plugin.py",
39
+ "src/anyio/itertools.py",
40
+ "src/anyio/to_interpreter.py",
41
+ "src/anyio/from_thread.py",
42
+ "src/anyio/to_process.py",
43
+ "src/anyio/to_thread.py",
44
+ "src/anyio/lowlevel.py",
45
+ "src/anyio/_backends/_trio.py",
46
+ "src/anyio/_backends/__init__.py",
47
+ "src/anyio/_backends/_asyncio.py",
48
+ "src/anyio/streams/memory.py",
49
+ "src/anyio/streams/__init__.py",
50
+ "src/anyio/streams/tls.py",
51
+ "src/anyio/streams/file.py",
52
+ "src/anyio/streams/text.py",
53
+ "src/anyio/streams/stapled.py",
54
+ "src/anyio/streams/buffered.py",
55
+ "src/anyio/abc/_eventloop.py",
56
+ "src/anyio/abc/__init__.py",
57
+ "src/anyio/abc/_sockets.py",
58
+ "src/anyio/abc/_tasks.py",
59
+ "src/anyio/abc/_subprocesses.py",
60
+ "src/anyio/abc/_resources.py",
61
+ "src/anyio/abc/_streams.py",
62
+ "src/anyio/abc/_testing.py",
63
+ "src/anyio/_core/_typedattr.py",
64
+ "src/anyio/_core/_eventloop.py",
65
+ "src/anyio/_core/__init__.py",
66
+ "src/anyio/_core/_tempfile.py",
67
+ "src/anyio/_core/_sockets.py",
68
+ "src/anyio/_core/_tasks.py",
69
+ "src/anyio/_core/_fileio.py",
70
+ "src/anyio/_core/_synchronization.py",
71
+ "src/anyio/_core/_subprocesses.py",
72
+ "src/anyio/_core/_resources.py",
73
+ "src/anyio/_core/_contextmanagers.py",
74
+ "src/anyio/_core/_exceptions.py",
75
+ "src/anyio/_core/_streams.py",
76
+ "src/anyio/_core/_signals.py",
77
+ "src/anyio/_core/_asyncio_selector_thread.py",
78
+ "src/anyio/_core/_testing.py",
79
+ "tests/test_itertools.py",
80
+ "tests/test_functools.py",
81
+ "tests/test_eventloop.py",
82
+ "tests/__init__.py",
83
+ "tests/test_to_thread.py",
84
+ "tests/test_from_thread.py",
85
+ "tests/test_lowlevel.py",
86
+ "tests/test_to_interpreter.py",
87
+ "tests/test_sockets.py",
88
+ "tests/test_typedattr.py",
89
+ "tests/test_to_process.py",
90
+ "tests/test_all_attributes.py",
91
+ "tests/test_synchronization.py",
92
+ "tests/test_debugging.py",
93
+ "tests/test_contextmanagers.py",
94
+ "tests/test_fileio.py",
95
+ "tests/conftest.py",
96
+ "tests/test_signals.py",
97
+ "tests/test_deprecations.py",
98
+ "tests/test_tempfile.py",
99
+ "tests/test_taskgroups.py",
100
+ "tests/test_pytest_plugin.py",
101
+ "tests/test_subprocesses.py",
102
+ "tests/streams/test_text.py",
103
+ "tests/streams/test_memory.py",
104
+ "tests/streams/__init__.py",
105
+ "tests/streams/test_file.py",
106
+ "tests/streams/test_stapled.py",
107
+ "tests/streams/test_tls.py",
108
+ "tests/streams/test_buffered.py",
109
+ ".github/pull_request_template.md",
110
+ ".github/dependabot.yml",
111
+ ".github/FUNDING.yml",
112
+ ".github/ISSUE_TEMPLATE/features_request.yaml",
113
+ ".github/ISSUE_TEMPLATE/bug_report.yaml",
114
+ ".github/ISSUE_TEMPLATE/config.yml",
115
+ ".github/workflows/test.yml",
116
+ ".github/workflows/test-downstream.yml",
117
+ ".github/workflows/publish.yml"
118
+ ]
119
+ }
.venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/scm_version.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tag": "4.14.2",
3
+ "distance": 0,
4
+ "node": "gc384f99687c64c59ed8a11c3a0f11a2d57daff71",
5
+ "dirty": false,
6
+ "branch": "HEAD",
7
+ "node_date": "2026-07-12"
8
+ }
.venv/lib/python3.13/site-packages/anyio-4.14.2.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ anyio
.venv/lib/python3.13/site-packages/anyio/__init__.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from ._core._contextmanagers import AsyncContextManagerMixin as AsyncContextManagerMixin
4
+ from ._core._contextmanagers import ContextManagerMixin as ContextManagerMixin
5
+ from ._core._eventloop import current_time as current_time
6
+ from ._core._eventloop import get_all_backends as get_all_backends
7
+ from ._core._eventloop import get_available_backends as get_available_backends
8
+ from ._core._eventloop import get_cancelled_exc_class as get_cancelled_exc_class
9
+ from ._core._eventloop import run as run
10
+ from ._core._eventloop import sleep as sleep
11
+ from ._core._eventloop import sleep_forever as sleep_forever
12
+ from ._core._eventloop import sleep_until as sleep_until
13
+ from ._core._exceptions import BrokenResourceError as BrokenResourceError
14
+ from ._core._exceptions import BrokenWorkerInterpreter as BrokenWorkerInterpreter
15
+ from ._core._exceptions import BrokenWorkerProcess as BrokenWorkerProcess
16
+ from ._core._exceptions import BusyResourceError as BusyResourceError
17
+ from ._core._exceptions import ClosedResourceError as ClosedResourceError
18
+ from ._core._exceptions import ConnectionFailed as ConnectionFailed
19
+ from ._core._exceptions import DelimiterNotFound as DelimiterNotFound
20
+ from ._core._exceptions import EndOfStream as EndOfStream
21
+ from ._core._exceptions import IncompleteRead as IncompleteRead
22
+ from ._core._exceptions import NoEventLoopError as NoEventLoopError
23
+ from ._core._exceptions import RunFinishedError as RunFinishedError
24
+ from ._core._exceptions import TaskCancelled as TaskCancelled
25
+ from ._core._exceptions import TaskFailed as TaskFailed
26
+ from ._core._exceptions import TaskNotFinished as TaskNotFinished
27
+ from ._core._exceptions import TypedAttributeLookupError as TypedAttributeLookupError
28
+ from ._core._exceptions import WouldBlock as WouldBlock
29
+ from ._core._fileio import AsyncFile as AsyncFile
30
+ from ._core._fileio import Path as Path
31
+ from ._core._fileio import open_file as open_file
32
+ from ._core._fileio import wrap_file as wrap_file
33
+ from ._core._resources import aclose_forcefully as aclose_forcefully
34
+ from ._core._signals import open_signal_receiver as open_signal_receiver
35
+ from ._core._sockets import TCPConnectable as TCPConnectable
36
+ from ._core._sockets import UNIXConnectable as UNIXConnectable
37
+ from ._core._sockets import as_connectable as as_connectable
38
+ from ._core._sockets import connect_tcp as connect_tcp
39
+ from ._core._sockets import connect_unix as connect_unix
40
+ from ._core._sockets import create_connected_udp_socket as create_connected_udp_socket
41
+ from ._core._sockets import (
42
+ create_connected_unix_datagram_socket as create_connected_unix_datagram_socket,
43
+ )
44
+ from ._core._sockets import create_tcp_listener as create_tcp_listener
45
+ from ._core._sockets import create_udp_socket as create_udp_socket
46
+ from ._core._sockets import create_unix_datagram_socket as create_unix_datagram_socket
47
+ from ._core._sockets import create_unix_listener as create_unix_listener
48
+ from ._core._sockets import getaddrinfo as getaddrinfo
49
+ from ._core._sockets import getnameinfo as getnameinfo
50
+ from ._core._sockets import notify_closing as notify_closing
51
+ from ._core._sockets import wait_readable as wait_readable
52
+ from ._core._sockets import wait_socket_readable as wait_socket_readable
53
+ from ._core._sockets import wait_socket_writable as wait_socket_writable
54
+ from ._core._sockets import wait_writable as wait_writable
55
+ from ._core._streams import create_memory_object_stream as create_memory_object_stream
56
+ from ._core._subprocesses import open_process as open_process
57
+ from ._core._subprocesses import run_process as run_process
58
+ from ._core._synchronization import CapacityLimiter as CapacityLimiter
59
+ from ._core._synchronization import (
60
+ CapacityLimiterStatistics as CapacityLimiterStatistics,
61
+ )
62
+ from ._core._synchronization import Condition as Condition
63
+ from ._core._synchronization import ConditionStatistics as ConditionStatistics
64
+ from ._core._synchronization import Event as Event
65
+ from ._core._synchronization import EventStatistics as EventStatistics
66
+ from ._core._synchronization import Lock as Lock
67
+ from ._core._synchronization import LockStatistics as LockStatistics
68
+ from ._core._synchronization import ResourceGuard as ResourceGuard
69
+ from ._core._synchronization import Semaphore as Semaphore
70
+ from ._core._synchronization import SemaphoreStatistics as SemaphoreStatistics
71
+ from ._core._tasks import TASK_STATUS_IGNORED as TASK_STATUS_IGNORED
72
+ from ._core._tasks import CancelScope as CancelScope
73
+ from ._core._tasks import TaskHandle as TaskHandle
74
+ from ._core._tasks import create_task_group as create_task_group
75
+ from ._core._tasks import current_effective_deadline as current_effective_deadline
76
+ from ._core._tasks import fail_after as fail_after
77
+ from ._core._tasks import move_on_after as move_on_after
78
+ from ._core._tempfile import NamedTemporaryFile as NamedTemporaryFile
79
+ from ._core._tempfile import SpooledTemporaryFile as SpooledTemporaryFile
80
+ from ._core._tempfile import TemporaryDirectory as TemporaryDirectory
81
+ from ._core._tempfile import TemporaryFile as TemporaryFile
82
+ from ._core._tempfile import gettempdir as gettempdir
83
+ from ._core._tempfile import gettempdirb as gettempdirb
84
+ from ._core._tempfile import mkdtemp as mkdtemp
85
+ from ._core._tempfile import mkstemp as mkstemp
86
+ from ._core._testing import TaskInfo as TaskInfo
87
+ from ._core._testing import get_current_task as get_current_task
88
+ from ._core._testing import get_running_tasks as get_running_tasks
89
+ from ._core._testing import wait_all_tasks_blocked as wait_all_tasks_blocked
90
+ from ._core._typedattr import TypedAttributeProvider as TypedAttributeProvider
91
+ from ._core._typedattr import TypedAttributeSet as TypedAttributeSet
92
+ from ._core._typedattr import typed_attribute as typed_attribute
93
+
94
+ # Re-export imports so they look like they live directly in this package
95
+ for __value in list(locals().values()):
96
+ if getattr(__value, "__module__", "").startswith("anyio."):
97
+ __value.__module__ = __name__
98
+
99
+
100
+ del __value
101
+
102
+
103
+ def __getattr__(attr: str) -> type[BrokenWorkerInterpreter]:
104
+ """Support deprecated aliases."""
105
+ if attr == "BrokenWorkerIntepreter":
106
+ import warnings
107
+
108
+ warnings.warn(
109
+ "The 'BrokenWorkerIntepreter' alias is deprecated, use 'BrokenWorkerInterpreter' instead.",
110
+ DeprecationWarning,
111
+ stacklevel=2,
112
+ )
113
+ return BrokenWorkerInterpreter
114
+
115
+ raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
.venv/lib/python3.13/site-packages/anyio/_backends/__init__.py ADDED
File without changes
.venv/lib/python3.13/site-packages/anyio/_backends/_asyncio.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.13/site-packages/anyio/_backends/_trio.py ADDED
@@ -0,0 +1,1468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import array
4
+ import math
5
+ import os
6
+ import socket
7
+ import sys
8
+ import types
9
+ import weakref
10
+ from collections.abc import (
11
+ AsyncGenerator,
12
+ AsyncIterator,
13
+ Awaitable,
14
+ Callable,
15
+ Collection,
16
+ Coroutine,
17
+ Iterable,
18
+ Sequence,
19
+ )
20
+ from contextlib import AbstractContextManager
21
+ from contextvars import Context
22
+ from dataclasses import dataclass
23
+ from functools import partial, wraps
24
+ from io import IOBase
25
+ from os import PathLike
26
+ from signal import Signals
27
+ from socket import AddressFamily, SocketKind
28
+ from types import TracebackType
29
+ from typing import (
30
+ IO,
31
+ TYPE_CHECKING,
32
+ Any,
33
+ Generic,
34
+ Literal,
35
+ NoReturn,
36
+ ParamSpec,
37
+ TypeVar,
38
+ cast,
39
+ overload,
40
+ )
41
+
42
+ import trio.from_thread
43
+ import trio.lowlevel
44
+ from outcome import Error, Outcome, Value
45
+ from trio.lowlevel import (
46
+ current_root_task,
47
+ current_task,
48
+ notify_closing,
49
+ wait_readable,
50
+ wait_writable,
51
+ )
52
+ from trio.socket import SocketType as TrioSocketType
53
+ from trio.to_thread import run_sync
54
+
55
+ from .. import (
56
+ CapacityLimiterStatistics,
57
+ EventStatistics,
58
+ LockStatistics,
59
+ RunFinishedError,
60
+ TaskInfo,
61
+ WouldBlock,
62
+ abc,
63
+ )
64
+ from .._core._eventloop import claim_worker_thread
65
+ from .._core._exceptions import (
66
+ BrokenResourceError,
67
+ BusyResourceError,
68
+ ClosedResourceError,
69
+ EndOfStream,
70
+ )
71
+ from .._core._sockets import convert_ipv6_sockaddr
72
+ from .._core._streams import create_memory_object_stream
73
+ from .._core._synchronization import (
74
+ CapacityLimiter as BaseCapacityLimiter,
75
+ )
76
+ from .._core._synchronization import Event as BaseEvent
77
+ from .._core._synchronization import Lock as BaseLock
78
+ from .._core._synchronization import (
79
+ ResourceGuard,
80
+ SemaphoreStatistics,
81
+ )
82
+ from .._core._synchronization import Semaphore as BaseSemaphore
83
+ from .._core._tasks import CancelScope as BaseCancelScope
84
+ from .._core._tasks import TaskHandle
85
+ from ..abc import IPSockAddrType, UDPPacketType, UNIXDatagramPacketType
86
+ from ..abc._eventloop import AsyncBackend, StrOrBytesPath
87
+ from ..abc._tasks import T_contra, call_for_coroutine, get_callable_name
88
+ from ..streams.memory import MemoryObjectSendStream
89
+
90
+ if TYPE_CHECKING:
91
+ from _typeshed import FileDescriptorLike
92
+
93
+ if sys.version_info >= (3, 11):
94
+ from typing import TypeVarTuple, Unpack
95
+ else:
96
+ from exceptiongroup import BaseExceptionGroup
97
+ from typing_extensions import TypeVarTuple, Unpack
98
+
99
+ T = TypeVar("T")
100
+ T_Retval = TypeVar("T_Retval")
101
+ T_co = TypeVar("T_co", covariant=True)
102
+ T_SockAddr = TypeVar("T_SockAddr", str, IPSockAddrType)
103
+ PosArgsT = TypeVarTuple("PosArgsT")
104
+ P = ParamSpec("P")
105
+
106
+
107
+ def ensure_returns_coro(
108
+ func: Callable[P, Awaitable[T_Retval]],
109
+ ) -> Callable[P, Coroutine[Any, Any, T_Retval]]:
110
+ @wraps(func)
111
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> Coroutine[Any, Any, T_Retval]:
112
+ awaitable = func(*args, **kwargs)
113
+ # Check the common case first.
114
+ if isinstance(awaitable, Coroutine):
115
+ return awaitable
116
+ elif not isinstance(awaitable, Awaitable):
117
+ # The user violated the type annotations. Still, we should pass this on to
118
+ # Trio so it can raise with an appropriate message.
119
+ return awaitable
120
+ else:
121
+
122
+ @wraps(func)
123
+ async def inner_wrapper() -> T_Retval:
124
+ return await awaitable
125
+
126
+ return inner_wrapper()
127
+
128
+ return wrapper
129
+
130
+
131
+ #
132
+ # Event loop
133
+ #
134
+
135
+ RunVar = trio.lowlevel.RunVar
136
+
137
+
138
+ #
139
+ # Timeouts and cancellation
140
+ #
141
+
142
+
143
+ class CancelScope(BaseCancelScope):
144
+ __slots__ = ("__original",)
145
+
146
+ def __new__(
147
+ cls, original: trio.CancelScope | None = None, **kwargs: object
148
+ ) -> CancelScope:
149
+ return object.__new__(cls)
150
+
151
+ def __init__(self, original: trio.CancelScope | None = None, **kwargs: Any) -> None:
152
+ self.__original = original or trio.CancelScope(**kwargs)
153
+
154
+ def __enter__(self) -> CancelScope:
155
+ self.__original.__enter__()
156
+ return self
157
+
158
+ def __exit__(
159
+ self,
160
+ exc_type: type[BaseException] | None,
161
+ exc_val: BaseException | None,
162
+ exc_tb: TracebackType | None,
163
+ ) -> bool:
164
+ return self.__original.__exit__(exc_type, exc_val, exc_tb)
165
+
166
+ def cancel(self, reason: str | None = None) -> None:
167
+ self.__original.cancel(reason)
168
+
169
+ @property
170
+ def deadline(self) -> float:
171
+ return self.__original.deadline
172
+
173
+ @deadline.setter
174
+ def deadline(self, value: float) -> None:
175
+ self.__original.deadline = value
176
+
177
+ @property
178
+ def cancel_called(self) -> bool:
179
+ return self.__original.cancel_called
180
+
181
+ @property
182
+ def cancelled_caught(self) -> bool:
183
+ return self.__original.cancelled_caught
184
+
185
+ @property
186
+ def shield(self) -> bool:
187
+ return self.__original.shield
188
+
189
+ @shield.setter
190
+ def shield(self, value: bool) -> None:
191
+ self.__original.shield = value
192
+
193
+
194
+ #
195
+ # Task groups
196
+ #
197
+
198
+ empty_start_value = object()
199
+
200
+
201
+ class _TrioTaskStatus(Generic[T_contra], abc.TaskStatus[T_contra]):
202
+ early_start_value: T_contra | object = empty_start_value
203
+ real_task_status: trio.TaskStatus[T_contra | None] | None = None
204
+
205
+ def started(self, value: T_contra | None = None) -> None:
206
+ if self.real_task_status is None:
207
+ if self.early_start_value is not empty_start_value:
208
+ raise RuntimeError("called 'started' twice on the same task status")
209
+
210
+ self.early_start_value = value
211
+ else:
212
+ self.real_task_status.started(value)
213
+
214
+
215
+ class TaskGroup(abc.TaskGroup):
216
+ def __init__(self) -> None:
217
+ self._entered = False
218
+ self._active = False
219
+ self._nursery_manager = trio.open_nursery(strict_exception_groups=True)
220
+ self.cancel_scope = None # type: ignore[assignment]
221
+
222
+ async def __aenter__(self) -> TaskGroup:
223
+ if self._entered:
224
+ raise RuntimeError("TaskGroup cannot be entered more than once")
225
+
226
+ self._entered = True
227
+ self._active = True
228
+ self._nursery = await self._nursery_manager.__aenter__()
229
+ self.cancel_scope = CancelScope(self._nursery.cancel_scope)
230
+ return self
231
+
232
+ async def __aexit__(
233
+ self,
234
+ exc_type: type[BaseException] | None,
235
+ exc_val: BaseException | None,
236
+ exc_tb: TracebackType | None,
237
+ ) -> bool:
238
+ try:
239
+ # trio.Nursery.__exit__ returns bool; .open_nursery has wrong type
240
+ return await self._nursery_manager.__aexit__(exc_type, exc_val, exc_tb) # type: ignore[return-value]
241
+ except BaseExceptionGroup as exc:
242
+ if not exc.split(trio.Cancelled)[1]:
243
+ raise trio.Cancelled._create() from exc
244
+
245
+ raise
246
+ finally:
247
+ del exc_val, exc_tb
248
+ self._active = False
249
+
250
+ def _check_active(self, coro: Coroutine | None = None) -> None:
251
+ if not self._active:
252
+ if coro is not None:
253
+ coro.close()
254
+
255
+ raise RuntimeError(
256
+ "This task group is not active; no new tasks can be started."
257
+ )
258
+
259
+ def create_task(
260
+ self,
261
+ coro: Coroutine[Any, Any, T_co],
262
+ *,
263
+ name: object = None,
264
+ context: Context | None = None,
265
+ ) -> TaskHandle[T_co]:
266
+ if not isinstance(coro, Coroutine):
267
+ raise TypeError(f"expected a coroutine, got {coro.__class__.__qualname__}")
268
+
269
+ self._check_active(coro)
270
+ handle = TaskHandle(coro, name)
271
+ if context is not None:
272
+ context.run(
273
+ partial(self._nursery.start_soon, handle._run_coro, name=handle.name)
274
+ )
275
+ else:
276
+ self._nursery.start_soon(handle._run_coro, name=handle.name)
277
+
278
+ return handle
279
+
280
+ async def start(
281
+ self,
282
+ func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]],
283
+ *args: Unpack[PosArgsT],
284
+ name: object = None,
285
+ return_handle: Literal[False] | Literal[True] = False,
286
+ ) -> Any:
287
+ handle: TaskHandle[T_co]
288
+
289
+ async def run_coro_with_task_status(
290
+ *, task_status: trio.TaskStatus[Any]
291
+ ) -> None:
292
+ nonlocal handle
293
+ wrapper_task_status = _TrioTaskStatus()
294
+ coro = call_for_coroutine(func, args, task_status=wrapper_task_status)
295
+ if wrapper_task_status.early_start_value is not empty_start_value:
296
+ task_status.started(wrapper_task_status.early_start_value)
297
+ else:
298
+ wrapper_task_status.real_task_status = task_status
299
+
300
+ handle = TaskHandle(coro, name)
301
+ await handle._run_coro()
302
+
303
+ self._check_active()
304
+ final_name = get_callable_name(func, name)
305
+ start_value = await self._nursery.start(
306
+ run_coro_with_task_status, name=final_name
307
+ )
308
+ if return_handle:
309
+ handle._start_value = start_value
310
+ return handle
311
+ else:
312
+ return start_value
313
+
314
+
315
+ #
316
+ # Subprocesses
317
+ #
318
+
319
+
320
+ @dataclass(eq=False)
321
+ class ReceiveStreamWrapper(abc.ByteReceiveStream):
322
+ _stream: trio.abc.ReceiveStream
323
+
324
+ async def receive(self, max_bytes: int | None = None) -> bytes:
325
+ if max_bytes is not None and max_bytes < 1:
326
+ raise ValueError("max_bytes must be a positive integer")
327
+
328
+ try:
329
+ data = await self._stream.receive_some(max_bytes)
330
+ except trio.ClosedResourceError as exc:
331
+ raise ClosedResourceError from exc.__cause__
332
+ except trio.BrokenResourceError as exc:
333
+ raise BrokenResourceError from exc.__cause__
334
+
335
+ if data:
336
+ return bytes(data)
337
+ else:
338
+ raise EndOfStream
339
+
340
+ async def aclose(self) -> None:
341
+ await self._stream.aclose()
342
+
343
+
344
+ @dataclass(eq=False)
345
+ class SendStreamWrapper(abc.ByteSendStream):
346
+ _stream: trio.abc.SendStream
347
+
348
+ async def send(self, item: bytes) -> None:
349
+ try:
350
+ await self._stream.send_all(item)
351
+ except trio.ClosedResourceError as exc:
352
+ raise ClosedResourceError from exc.__cause__
353
+ except trio.BrokenResourceError as exc:
354
+ raise BrokenResourceError from exc.__cause__
355
+
356
+ async def aclose(self) -> None:
357
+ await self._stream.aclose()
358
+
359
+
360
+ @dataclass(eq=False)
361
+ class Process(abc.Process):
362
+ _process: trio.Process
363
+ _stdin: abc.ByteSendStream | None
364
+ _stdout: abc.ByteReceiveStream | None
365
+ _stderr: abc.ByteReceiveStream | None
366
+
367
+ async def aclose(self) -> None:
368
+ with CancelScope(shield=True):
369
+ if self._stdin:
370
+ await self._stdin.aclose()
371
+ if self._stdout:
372
+ await self._stdout.aclose()
373
+ if self._stderr:
374
+ await self._stderr.aclose()
375
+
376
+ try:
377
+ await self.wait()
378
+ except BaseException:
379
+ self.kill()
380
+ with CancelScope(shield=True):
381
+ await self.wait()
382
+ raise
383
+
384
+ async def wait(self) -> int:
385
+ return await self._process.wait()
386
+
387
+ def terminate(self) -> None:
388
+ self._process.terminate()
389
+
390
+ def kill(self) -> None:
391
+ self._process.kill()
392
+
393
+ def send_signal(self, signal: Signals) -> None:
394
+ self._process.send_signal(signal)
395
+
396
+ @property
397
+ def pid(self) -> int:
398
+ return self._process.pid
399
+
400
+ @property
401
+ def returncode(self) -> int | None:
402
+ return self._process.returncode
403
+
404
+ @property
405
+ def stdin(self) -> abc.ByteSendStream | None:
406
+ return self._stdin
407
+
408
+ @property
409
+ def stdout(self) -> abc.ByteReceiveStream | None:
410
+ return self._stdout
411
+
412
+ @property
413
+ def stderr(self) -> abc.ByteReceiveStream | None:
414
+ return self._stderr
415
+
416
+
417
+ class _ProcessPoolShutdownInstrument(trio.abc.Instrument):
418
+ def after_run(self) -> None:
419
+ super().after_run()
420
+
421
+
422
+ current_default_worker_process_limiter: trio.lowlevel.RunVar = RunVar(
423
+ "current_default_worker_process_limiter"
424
+ )
425
+
426
+
427
+ async def _shutdown_process_pool(workers: set[abc.Process]) -> None:
428
+ try:
429
+ await trio.sleep(math.inf)
430
+ except trio.Cancelled:
431
+ for process in workers:
432
+ if process.returncode is None:
433
+ process.kill()
434
+
435
+ with CancelScope(shield=True):
436
+ for process in workers:
437
+ await process.aclose()
438
+
439
+
440
+ #
441
+ # Sockets and networking
442
+ #
443
+
444
+
445
+ class _TrioSocketMixin(Generic[T_SockAddr]):
446
+ def __init__(self, trio_socket: TrioSocketType) -> None:
447
+ self._trio_socket = trio_socket
448
+ self._closed = False
449
+
450
+ def _check_closed(self) -> None:
451
+ if self._closed:
452
+ raise ClosedResourceError
453
+ if self._trio_socket.fileno() < 0:
454
+ raise BrokenResourceError
455
+
456
+ @property
457
+ def _raw_socket(self) -> socket.socket:
458
+ return self._trio_socket._sock # type: ignore[attr-defined]
459
+
460
+ async def aclose(self) -> None:
461
+ if self._trio_socket.fileno() >= 0:
462
+ self._closed = True
463
+ self._trio_socket.close()
464
+
465
+ def _convert_socket_error(self, exc: BaseException) -> NoReturn:
466
+ if isinstance(exc, trio.ClosedResourceError):
467
+ raise ClosedResourceError from exc
468
+ elif self._trio_socket.fileno() < 0 and self._closed:
469
+ raise ClosedResourceError from None
470
+ elif isinstance(exc, OSError):
471
+ raise BrokenResourceError from exc
472
+ else:
473
+ raise exc
474
+
475
+
476
+ class SocketStream(_TrioSocketMixin, abc.SocketStream):
477
+ def __init__(self, trio_socket: TrioSocketType) -> None:
478
+ super().__init__(trio_socket)
479
+ self._receive_guard = ResourceGuard("reading from")
480
+ self._send_guard = ResourceGuard("writing to")
481
+
482
+ async def receive(self, max_bytes: int = 65536) -> bytes:
483
+ if max_bytes < 1:
484
+ raise ValueError("max_bytes must be a positive integer")
485
+
486
+ with self._receive_guard:
487
+ try:
488
+ data = await self._trio_socket.recv(max_bytes)
489
+ except BaseException as exc:
490
+ self._convert_socket_error(exc)
491
+
492
+ if data:
493
+ return data
494
+ else:
495
+ raise EndOfStream
496
+
497
+ async def send(self, item: bytes) -> None:
498
+ with self._send_guard:
499
+ view = memoryview(item)
500
+ while view:
501
+ try:
502
+ bytes_sent = await self._trio_socket.send(view)
503
+ except BaseException as exc:
504
+ self._convert_socket_error(exc)
505
+
506
+ view = view[bytes_sent:]
507
+
508
+ async def send_eof(self) -> None:
509
+ self._trio_socket.shutdown(socket.SHUT_WR)
510
+
511
+
512
+ class UNIXSocketStream(SocketStream, abc.UNIXSocketStream):
513
+ async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]:
514
+ if not isinstance(msglen, int) or msglen < 0:
515
+ raise ValueError("msglen must be a non-negative integer")
516
+ if not isinstance(maxfds, int) or maxfds < 1:
517
+ raise ValueError("maxfds must be a positive integer")
518
+
519
+ fds = array.array("i")
520
+ await trio.lowlevel.checkpoint()
521
+ with self._receive_guard:
522
+ while True:
523
+ try:
524
+ message, ancdata, flags, addr = await self._trio_socket.recvmsg(
525
+ msglen, socket.CMSG_LEN(maxfds * fds.itemsize)
526
+ )
527
+ except BaseException as exc:
528
+ self._convert_socket_error(exc)
529
+ else:
530
+ if not message and not ancdata:
531
+ raise EndOfStream
532
+
533
+ break
534
+
535
+ for cmsg_level, cmsg_type, cmsg_data in ancdata:
536
+ if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS:
537
+ raise RuntimeError(
538
+ f"Received unexpected ancillary data; message = {message!r}, "
539
+ f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}"
540
+ )
541
+
542
+ fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
543
+
544
+ return message, list(fds)
545
+
546
+ async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None:
547
+ if not message:
548
+ raise ValueError("message must not be empty")
549
+ if not fds:
550
+ raise ValueError("fds must not be empty")
551
+
552
+ filenos: list[int] = []
553
+ for fd in fds:
554
+ if isinstance(fd, int):
555
+ filenos.append(fd)
556
+ elif isinstance(fd, IOBase):
557
+ filenos.append(fd.fileno())
558
+
559
+ fdarray = array.array("i", filenos)
560
+ await trio.lowlevel.checkpoint()
561
+ with self._send_guard:
562
+ while True:
563
+ try:
564
+ await self._trio_socket.sendmsg(
565
+ [message],
566
+ [
567
+ (
568
+ socket.SOL_SOCKET,
569
+ socket.SCM_RIGHTS,
570
+ fdarray,
571
+ )
572
+ ],
573
+ )
574
+ break
575
+ except BaseException as exc:
576
+ self._convert_socket_error(exc)
577
+
578
+
579
+ class TCPSocketListener(_TrioSocketMixin, abc.SocketListener):
580
+ def __init__(self, raw_socket: socket.socket):
581
+ super().__init__(trio.socket.from_stdlib_socket(raw_socket))
582
+ self._accept_guard = ResourceGuard("accepting connections from")
583
+
584
+ async def accept(self) -> SocketStream:
585
+ with self._accept_guard:
586
+ try:
587
+ trio_socket, _addr = await self._trio_socket.accept()
588
+ except BaseException as exc:
589
+ self._convert_socket_error(exc)
590
+
591
+ trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
592
+ return SocketStream(trio_socket)
593
+
594
+
595
+ class UNIXSocketListener(_TrioSocketMixin, abc.SocketListener):
596
+ def __init__(self, raw_socket: socket.socket):
597
+ super().__init__(trio.socket.from_stdlib_socket(raw_socket))
598
+ self._accept_guard = ResourceGuard("accepting connections from")
599
+
600
+ async def accept(self) -> UNIXSocketStream:
601
+ with self._accept_guard:
602
+ try:
603
+ trio_socket, _addr = await self._trio_socket.accept()
604
+ except BaseException as exc:
605
+ self._convert_socket_error(exc)
606
+
607
+ return UNIXSocketStream(trio_socket)
608
+
609
+
610
+ class UDPSocket(_TrioSocketMixin[IPSockAddrType], abc.UDPSocket):
611
+ def __init__(self, trio_socket: TrioSocketType) -> None:
612
+ super().__init__(trio_socket)
613
+ self._receive_guard = ResourceGuard("reading from")
614
+ self._send_guard = ResourceGuard("writing to")
615
+
616
+ async def receive(self) -> tuple[bytes, IPSockAddrType]:
617
+ with self._receive_guard:
618
+ try:
619
+ data, addr = await self._trio_socket.recvfrom(65536)
620
+ return data, convert_ipv6_sockaddr(addr)
621
+ except BaseException as exc:
622
+ self._convert_socket_error(exc)
623
+
624
+ async def send(self, item: UDPPacketType) -> None:
625
+ with self._send_guard:
626
+ try:
627
+ await self._trio_socket.sendto(*item)
628
+ except BaseException as exc:
629
+ self._convert_socket_error(exc)
630
+
631
+
632
+ class ConnectedUDPSocket(_TrioSocketMixin[IPSockAddrType], abc.ConnectedUDPSocket):
633
+ def __init__(self, trio_socket: TrioSocketType) -> None:
634
+ super().__init__(trio_socket)
635
+ self._receive_guard = ResourceGuard("reading from")
636
+ self._send_guard = ResourceGuard("writing to")
637
+
638
+ async def receive(self) -> bytes:
639
+ with self._receive_guard:
640
+ try:
641
+ return await self._trio_socket.recv(65536)
642
+ except BaseException as exc:
643
+ self._convert_socket_error(exc)
644
+
645
+ async def send(self, item: bytes) -> None:
646
+ with self._send_guard:
647
+ try:
648
+ await self._trio_socket.send(item)
649
+ except BaseException as exc:
650
+ self._convert_socket_error(exc)
651
+
652
+
653
+ class UNIXDatagramSocket(_TrioSocketMixin[str], abc.UNIXDatagramSocket):
654
+ def __init__(self, trio_socket: TrioSocketType) -> None:
655
+ super().__init__(trio_socket)
656
+ self._receive_guard = ResourceGuard("reading from")
657
+ self._send_guard = ResourceGuard("writing to")
658
+
659
+ async def receive(self) -> UNIXDatagramPacketType:
660
+ with self._receive_guard:
661
+ try:
662
+ data, addr = await self._trio_socket.recvfrom(65536)
663
+ return data, addr
664
+ except BaseException as exc:
665
+ self._convert_socket_error(exc)
666
+
667
+ async def send(self, item: UNIXDatagramPacketType) -> None:
668
+ with self._send_guard:
669
+ try:
670
+ await self._trio_socket.sendto(*item)
671
+ except BaseException as exc:
672
+ self._convert_socket_error(exc)
673
+
674
+
675
+ class ConnectedUNIXDatagramSocket(
676
+ _TrioSocketMixin[str], abc.ConnectedUNIXDatagramSocket
677
+ ):
678
+ def __init__(self, trio_socket: TrioSocketType) -> None:
679
+ super().__init__(trio_socket)
680
+ self._receive_guard = ResourceGuard("reading from")
681
+ self._send_guard = ResourceGuard("writing to")
682
+
683
+ async def receive(self) -> bytes:
684
+ with self._receive_guard:
685
+ try:
686
+ return await self._trio_socket.recv(65536)
687
+ except BaseException as exc:
688
+ self._convert_socket_error(exc)
689
+
690
+ async def send(self, item: bytes) -> None:
691
+ with self._send_guard:
692
+ try:
693
+ await self._trio_socket.send(item)
694
+ except BaseException as exc:
695
+ self._convert_socket_error(exc)
696
+
697
+
698
+ #
699
+ # Synchronization
700
+ #
701
+
702
+
703
+ class Event(BaseEvent):
704
+ __slots__ = ("__original",)
705
+
706
+ def __new__(cls) -> Event:
707
+ return object.__new__(cls)
708
+
709
+ def __init__(self) -> None:
710
+ self.__original = trio.Event()
711
+
712
+ def is_set(self) -> bool:
713
+ return self.__original.is_set()
714
+
715
+ async def wait(self) -> None:
716
+ return await self.__original.wait()
717
+
718
+ def statistics(self) -> EventStatistics:
719
+ orig_statistics = self.__original.statistics()
720
+ return EventStatistics(tasks_waiting=orig_statistics.tasks_waiting)
721
+
722
+ def set(self) -> None:
723
+ self.__original.set()
724
+
725
+
726
+ class Lock(BaseLock):
727
+ __slots__ = "_fast_acquire", "__original"
728
+
729
+ def __new__(cls, *, fast_acquire: bool = False) -> Lock:
730
+ return object.__new__(cls)
731
+
732
+ def __init__(self, *, fast_acquire: bool = False) -> None:
733
+ self._fast_acquire = fast_acquire
734
+ self.__original = trio.Lock()
735
+
736
+ @staticmethod
737
+ def _convert_runtime_error_msg(exc: RuntimeError) -> None:
738
+ if exc.args == ("attempt to re-acquire an already held Lock",):
739
+ exc.args = ("Attempted to acquire an already held Lock",)
740
+
741
+ async def acquire(self) -> None:
742
+ if not self._fast_acquire:
743
+ try:
744
+ await self.__original.acquire()
745
+ except RuntimeError as exc:
746
+ self._convert_runtime_error_msg(exc)
747
+ raise
748
+
749
+ return
750
+
751
+ # This is the "fast path" where we don't let other tasks run
752
+ await trio.lowlevel.checkpoint_if_cancelled()
753
+ try:
754
+ self.__original.acquire_nowait()
755
+ except trio.WouldBlock:
756
+ await self.__original._lot.park()
757
+ except RuntimeError as exc:
758
+ self._convert_runtime_error_msg(exc)
759
+ raise
760
+
761
+ def acquire_nowait(self) -> None:
762
+ try:
763
+ self.__original.acquire_nowait()
764
+ except trio.WouldBlock:
765
+ raise WouldBlock from None
766
+ except RuntimeError as exc:
767
+ self._convert_runtime_error_msg(exc)
768
+ raise
769
+
770
+ def locked(self) -> bool:
771
+ return self.__original.locked()
772
+
773
+ def release(self) -> None:
774
+ self.__original.release()
775
+
776
+ def statistics(self) -> LockStatistics:
777
+ orig_statistics = self.__original.statistics()
778
+ owner = TrioTaskInfo(orig_statistics.owner) if orig_statistics.owner else None
779
+ return LockStatistics(
780
+ orig_statistics.locked, owner, orig_statistics.tasks_waiting
781
+ )
782
+
783
+
784
+ class Semaphore(BaseSemaphore):
785
+ __slots__ = ("__original",)
786
+
787
+ def __new__(
788
+ cls,
789
+ initial_value: int,
790
+ *,
791
+ max_value: int | None = None,
792
+ fast_acquire: bool = False,
793
+ ) -> Semaphore:
794
+ return object.__new__(cls)
795
+
796
+ def __init__(
797
+ self,
798
+ initial_value: int,
799
+ *,
800
+ max_value: int | None = None,
801
+ fast_acquire: bool = False,
802
+ ) -> None:
803
+ super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire)
804
+ self.__original = trio.Semaphore(initial_value, max_value=max_value)
805
+
806
+ async def acquire(self) -> None:
807
+ if not self._fast_acquire:
808
+ await self.__original.acquire()
809
+ return
810
+
811
+ # This is the "fast path" where we don't let other tasks run
812
+ await trio.lowlevel.checkpoint_if_cancelled()
813
+ try:
814
+ self.__original.acquire_nowait()
815
+ except trio.WouldBlock:
816
+ await self.__original._lot.park()
817
+
818
+ def acquire_nowait(self) -> None:
819
+ try:
820
+ self.__original.acquire_nowait()
821
+ except trio.WouldBlock:
822
+ raise WouldBlock from None
823
+
824
+ @property
825
+ def max_value(self) -> int | None:
826
+ return self.__original.max_value
827
+
828
+ @property
829
+ def value(self) -> int:
830
+ return self.__original.value
831
+
832
+ def release(self) -> None:
833
+ self.__original.release()
834
+
835
+ def statistics(self) -> SemaphoreStatistics:
836
+ orig_statistics = self.__original.statistics()
837
+ return SemaphoreStatistics(orig_statistics.tasks_waiting)
838
+
839
+
840
+ class CapacityLimiter(BaseCapacityLimiter):
841
+ __slots__ = ("__original",)
842
+
843
+ def __new__(
844
+ cls,
845
+ total_tokens: float | None = None,
846
+ *,
847
+ original: trio.CapacityLimiter | None = None,
848
+ ) -> CapacityLimiter:
849
+ return object.__new__(cls)
850
+
851
+ def __init__(
852
+ self,
853
+ total_tokens: float | None = None,
854
+ *,
855
+ original: trio.CapacityLimiter | None = None,
856
+ ) -> None:
857
+ if original is not None:
858
+ self.__original = original
859
+ else:
860
+ assert total_tokens is not None
861
+ self.__original = trio.CapacityLimiter(total_tokens)
862
+
863
+ async def __aenter__(self) -> None:
864
+ return await self.__original.__aenter__()
865
+
866
+ async def __aexit__(
867
+ self,
868
+ exc_type: type[BaseException] | None,
869
+ exc_val: BaseException | None,
870
+ exc_tb: TracebackType | None,
871
+ ) -> None:
872
+ await self.__original.__aexit__(exc_type, exc_val, exc_tb)
873
+
874
+ @property
875
+ def total_tokens(self) -> float:
876
+ return self.__original.total_tokens
877
+
878
+ @total_tokens.setter
879
+ def total_tokens(self, value: float) -> None:
880
+ self.__original.total_tokens = value
881
+
882
+ @property
883
+ def borrowed_tokens(self) -> int:
884
+ return self.__original.borrowed_tokens
885
+
886
+ @property
887
+ def available_tokens(self) -> float:
888
+ return self.__original.available_tokens
889
+
890
+ def acquire_nowait(self) -> None:
891
+ try:
892
+ self.__original.acquire_nowait()
893
+ except trio.WouldBlock:
894
+ raise WouldBlock from None
895
+
896
+ def acquire_on_behalf_of_nowait(self, borrower: object) -> None:
897
+ try:
898
+ self.__original.acquire_on_behalf_of_nowait(borrower)
899
+ except trio.WouldBlock:
900
+ raise WouldBlock from None
901
+
902
+ async def acquire(self) -> None:
903
+ await self.__original.acquire()
904
+
905
+ async def acquire_on_behalf_of(self, borrower: object) -> None:
906
+ await self.__original.acquire_on_behalf_of(borrower)
907
+
908
+ def release(self) -> None:
909
+ return self.__original.release()
910
+
911
+ def release_on_behalf_of(self, borrower: object) -> None:
912
+ return self.__original.release_on_behalf_of(borrower)
913
+
914
+ def statistics(self) -> CapacityLimiterStatistics:
915
+ orig = self.__original.statistics()
916
+ return CapacityLimiterStatistics(
917
+ borrowed_tokens=orig.borrowed_tokens,
918
+ total_tokens=orig.total_tokens,
919
+ borrowers=tuple(orig.borrowers),
920
+ tasks_waiting=orig.tasks_waiting,
921
+ )
922
+
923
+
924
+ _capacity_limiter_wrapper: trio.lowlevel.RunVar = RunVar("_capacity_limiter_wrapper")
925
+
926
+
927
+ #
928
+ # Signal handling
929
+ #
930
+
931
+
932
+ class _SignalReceiver:
933
+ _iterator: AsyncIterator[int]
934
+
935
+ def __init__(self, signals: tuple[Signals, ...]):
936
+ self._signals = signals
937
+
938
+ def __enter__(self) -> _SignalReceiver:
939
+ self._cm = trio.open_signal_receiver(*self._signals)
940
+ self._iterator = self._cm.__enter__()
941
+ return self
942
+
943
+ def __exit__(
944
+ self,
945
+ exc_type: type[BaseException] | None,
946
+ exc_val: BaseException | None,
947
+ exc_tb: TracebackType | None,
948
+ ) -> bool | None:
949
+ return self._cm.__exit__(exc_type, exc_val, exc_tb)
950
+
951
+ def __aiter__(self) -> _SignalReceiver:
952
+ return self
953
+
954
+ async def __anext__(self) -> Signals:
955
+ signum = await self._iterator.__anext__()
956
+ return Signals(signum)
957
+
958
+
959
+ #
960
+ # Testing and debugging
961
+ #
962
+
963
+
964
+ class TestRunner(abc.TestRunner):
965
+ def __init__(self, **options: Any) -> None:
966
+ from queue import Queue
967
+
968
+ self._call_queue: Queue[Callable[[], object]] = Queue()
969
+ self._send_stream: (
970
+ MemoryObjectSendStream[tuple[Awaitable[Any], list[Outcome]]] | None
971
+ ) = None
972
+ self._options = options
973
+
974
+ def __exit__(
975
+ self,
976
+ exc_type: type[BaseException] | None,
977
+ exc_val: BaseException | None,
978
+ exc_tb: types.TracebackType | None,
979
+ ) -> None:
980
+ if self._send_stream:
981
+ self._send_stream.close()
982
+ while self._send_stream is not None:
983
+ self._call_queue.get()()
984
+
985
+ def is_running(self) -> bool:
986
+ return trio.lowlevel.in_trio_task()
987
+
988
+ async def _run_tests_and_fixtures(self) -> None:
989
+ self._send_stream, receive_stream = create_memory_object_stream[
990
+ tuple[Awaitable[Any], list[Outcome]]
991
+ ](1)
992
+ with receive_stream:
993
+ async for awaitable, outcome_holder in receive_stream:
994
+ try:
995
+ retval = await awaitable
996
+ except BaseException as exc:
997
+ outcome_holder.append(Error(exc))
998
+ else:
999
+ outcome_holder.append(Value(retval))
1000
+
1001
+ def _main_task_finished(self, outcome: object) -> None:
1002
+ self._send_stream = None
1003
+
1004
+ def _call_in_runner_task(
1005
+ self,
1006
+ func: Callable[P, Awaitable[T_Retval]],
1007
+ /,
1008
+ *args: P.args,
1009
+ **kwargs: P.kwargs,
1010
+ ) -> T_Retval:
1011
+ if self._send_stream is None:
1012
+ trio.lowlevel.start_guest_run(
1013
+ self._run_tests_and_fixtures,
1014
+ run_sync_soon_threadsafe=self._call_queue.put,
1015
+ done_callback=self._main_task_finished,
1016
+ **self._options,
1017
+ )
1018
+ while self._send_stream is None:
1019
+ self._call_queue.get()()
1020
+
1021
+ outcome_holder: list[Outcome] = []
1022
+ self._send_stream.send_nowait((func(*args, **kwargs), outcome_holder))
1023
+ while not outcome_holder:
1024
+ self._call_queue.get()()
1025
+
1026
+ return outcome_holder[0].unwrap()
1027
+
1028
+ def run_asyncgen_fixture(
1029
+ self,
1030
+ fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]],
1031
+ kwargs: dict[str, Any],
1032
+ ) -> Iterable[T_Retval]:
1033
+ asyncgen = fixture_func(**kwargs)
1034
+ fixturevalue: T_Retval = self._call_in_runner_task(asyncgen.asend, None)
1035
+
1036
+ yield fixturevalue
1037
+
1038
+ try:
1039
+ self._call_in_runner_task(asyncgen.asend, None)
1040
+ except StopAsyncIteration:
1041
+ pass
1042
+ else:
1043
+ self._call_in_runner_task(asyncgen.aclose)
1044
+ raise RuntimeError("Async generator fixture did not stop")
1045
+
1046
+ def run_fixture(
1047
+ self,
1048
+ fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]],
1049
+ kwargs: dict[str, Any],
1050
+ ) -> T_Retval:
1051
+ return self._call_in_runner_task(fixture_func, **kwargs)
1052
+
1053
+ def run_test(
1054
+ self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any]
1055
+ ) -> None:
1056
+ self._call_in_runner_task(test_func, **kwargs)
1057
+
1058
+
1059
+ class TrioTaskInfo(TaskInfo):
1060
+ def __init__(self, task: trio.lowlevel.Task):
1061
+ parent_id = None
1062
+ if task.parent_nursery and task.parent_nursery.parent_task:
1063
+ parent_id = id(task.parent_nursery.parent_task)
1064
+
1065
+ super().__init__(id(task), parent_id, task.name, task.coro)
1066
+ self._task = weakref.proxy(task)
1067
+
1068
+ def has_pending_cancellation(self) -> bool:
1069
+ try:
1070
+ return self._task._cancel_status.effectively_cancelled
1071
+ except ReferenceError:
1072
+ # If the task is no longer around, it surely doesn't have a cancellation
1073
+ # pending
1074
+ return False
1075
+
1076
+
1077
+ class TrioBackend(AsyncBackend):
1078
+ @classmethod
1079
+ def run(
1080
+ cls,
1081
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
1082
+ args: tuple[Unpack[PosArgsT]],
1083
+ kwargs: dict[str, Any],
1084
+ options: dict[str, Any],
1085
+ ) -> T_Retval:
1086
+ assert not kwargs, "unreachable, and not supported by Trio"
1087
+ return trio.run(ensure_returns_coro(func), *args, **options)
1088
+
1089
+ @classmethod
1090
+ def current_token(cls) -> object:
1091
+ return trio.lowlevel.current_trio_token()
1092
+
1093
+ @classmethod
1094
+ def current_time(cls) -> float:
1095
+ return trio.current_time()
1096
+
1097
+ @classmethod
1098
+ def cancelled_exception_class(cls) -> type[BaseException]:
1099
+ return trio.Cancelled
1100
+
1101
+ @classmethod
1102
+ async def checkpoint(cls) -> None:
1103
+ await trio.lowlevel.checkpoint()
1104
+
1105
+ @classmethod
1106
+ async def checkpoint_if_cancelled(cls) -> None:
1107
+ await trio.lowlevel.checkpoint_if_cancelled()
1108
+
1109
+ @classmethod
1110
+ async def cancel_shielded_checkpoint(cls) -> None:
1111
+ await trio.lowlevel.cancel_shielded_checkpoint()
1112
+
1113
+ @classmethod
1114
+ async def sleep(cls, delay: float) -> None:
1115
+ await trio.sleep(delay)
1116
+
1117
+ @classmethod
1118
+ def create_cancel_scope(
1119
+ cls, *, deadline: float = math.inf, shield: bool = False
1120
+ ) -> abc.CancelScope:
1121
+ return CancelScope(deadline=deadline, shield=shield)
1122
+
1123
+ @classmethod
1124
+ def current_effective_deadline(cls) -> float:
1125
+ return trio.current_effective_deadline()
1126
+
1127
+ @classmethod
1128
+ def create_task_group(cls) -> abc.TaskGroup:
1129
+ return TaskGroup()
1130
+
1131
+ @classmethod
1132
+ def create_event(cls) -> abc.Event:
1133
+ return Event()
1134
+
1135
+ @classmethod
1136
+ def create_lock(cls, *, fast_acquire: bool) -> Lock:
1137
+ return Lock(fast_acquire=fast_acquire)
1138
+
1139
+ @classmethod
1140
+ def create_semaphore(
1141
+ cls,
1142
+ initial_value: int,
1143
+ *,
1144
+ max_value: int | None = None,
1145
+ fast_acquire: bool = False,
1146
+ ) -> abc.Semaphore:
1147
+ return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire)
1148
+
1149
+ @classmethod
1150
+ def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter:
1151
+ return CapacityLimiter(total_tokens)
1152
+
1153
+ @classmethod
1154
+ async def run_sync_in_worker_thread(
1155
+ cls,
1156
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
1157
+ args: tuple[Unpack[PosArgsT]],
1158
+ abandon_on_cancel: bool = False,
1159
+ limiter: abc.CapacityLimiter | None = None,
1160
+ ) -> T_Retval:
1161
+ def wrapper() -> T_Retval:
1162
+ with claim_worker_thread(TrioBackend, token):
1163
+ return func(*args)
1164
+
1165
+ token = TrioBackend.current_token()
1166
+ return await run_sync(
1167
+ wrapper,
1168
+ abandon_on_cancel=abandon_on_cancel,
1169
+ limiter=cast(trio.CapacityLimiter, limiter),
1170
+ )
1171
+
1172
+ @classmethod
1173
+ def check_cancelled(cls) -> None:
1174
+ trio.from_thread.check_cancelled()
1175
+
1176
+ @classmethod
1177
+ def run_async_from_thread(
1178
+ cls,
1179
+ func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]],
1180
+ args: tuple[Unpack[PosArgsT]],
1181
+ token: object,
1182
+ ) -> T_co:
1183
+ trio_token = cast("trio.lowlevel.TrioToken | None", token)
1184
+ try:
1185
+ return trio.from_thread.run(func, *args, trio_token=trio_token)
1186
+ except trio.RunFinishedError:
1187
+ raise RunFinishedError from None
1188
+
1189
+ @classmethod
1190
+ def run_sync_from_thread(
1191
+ cls,
1192
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
1193
+ args: tuple[Unpack[PosArgsT]],
1194
+ token: object,
1195
+ ) -> T_Retval:
1196
+ trio_token = cast("trio.lowlevel.TrioToken | None", token)
1197
+ try:
1198
+ return trio.from_thread.run_sync(func, *args, trio_token=trio_token)
1199
+ except trio.RunFinishedError:
1200
+ raise RunFinishedError from None
1201
+
1202
+ @classmethod
1203
+ async def open_process(
1204
+ cls,
1205
+ command: StrOrBytesPath | Sequence[StrOrBytesPath],
1206
+ *,
1207
+ stdin: int | IO[Any] | None,
1208
+ stdout: int | IO[Any] | None,
1209
+ stderr: int | IO[Any] | None,
1210
+ **kwargs: Any,
1211
+ ) -> Process:
1212
+ def convert_item(item: StrOrBytesPath) -> str:
1213
+ str_or_bytes = os.fspath(item)
1214
+ if isinstance(str_or_bytes, str):
1215
+ return str_or_bytes
1216
+ else:
1217
+ return os.fsdecode(str_or_bytes)
1218
+
1219
+ if isinstance(command, (str, bytes, PathLike)):
1220
+ process = await trio.lowlevel.open_process(
1221
+ convert_item(command),
1222
+ stdin=stdin,
1223
+ stdout=stdout,
1224
+ stderr=stderr,
1225
+ shell=True,
1226
+ **kwargs,
1227
+ )
1228
+ else:
1229
+ process = await trio.lowlevel.open_process(
1230
+ [convert_item(item) for item in command],
1231
+ stdin=stdin,
1232
+ stdout=stdout,
1233
+ stderr=stderr,
1234
+ shell=False,
1235
+ **kwargs,
1236
+ )
1237
+
1238
+ stdin_stream = SendStreamWrapper(process.stdin) if process.stdin else None
1239
+ stdout_stream = ReceiveStreamWrapper(process.stdout) if process.stdout else None
1240
+ stderr_stream = ReceiveStreamWrapper(process.stderr) if process.stderr else None
1241
+ return Process(process, stdin_stream, stdout_stream, stderr_stream)
1242
+
1243
+ @classmethod
1244
+ def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None:
1245
+ trio.lowlevel.spawn_system_task(_shutdown_process_pool, workers)
1246
+
1247
+ @classmethod
1248
+ async def connect_tcp(
1249
+ cls, host: str, port: int, local_address: IPSockAddrType | None = None
1250
+ ) -> SocketStream:
1251
+ family = socket.AF_INET6 if ":" in host else socket.AF_INET
1252
+ trio_socket = trio.socket.socket(family)
1253
+ trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
1254
+ if local_address:
1255
+ await trio_socket.bind(local_address)
1256
+
1257
+ try:
1258
+ await trio_socket.connect((host, port))
1259
+ except BaseException:
1260
+ trio_socket.close()
1261
+ raise
1262
+
1263
+ return SocketStream(trio_socket)
1264
+
1265
+ @classmethod
1266
+ async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream:
1267
+ trio_socket = trio.socket.socket(socket.AF_UNIX)
1268
+ try:
1269
+ await trio_socket.connect(path)
1270
+ except BaseException:
1271
+ trio_socket.close()
1272
+ raise
1273
+
1274
+ return UNIXSocketStream(trio_socket)
1275
+
1276
+ @classmethod
1277
+ def create_tcp_listener(cls, sock: socket.socket) -> abc.SocketListener:
1278
+ return TCPSocketListener(sock)
1279
+
1280
+ @classmethod
1281
+ def create_unix_listener(cls, sock: socket.socket) -> abc.SocketListener:
1282
+ return UNIXSocketListener(sock)
1283
+
1284
+ @classmethod
1285
+ async def create_udp_socket(
1286
+ cls,
1287
+ family: socket.AddressFamily,
1288
+ local_address: IPSockAddrType | None,
1289
+ remote_address: IPSockAddrType | None,
1290
+ reuse_port: bool,
1291
+ ) -> UDPSocket | ConnectedUDPSocket:
1292
+ trio_socket = trio.socket.socket(family=family, type=socket.SOCK_DGRAM)
1293
+
1294
+ if reuse_port:
1295
+ trio_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
1296
+
1297
+ if local_address:
1298
+ await trio_socket.bind(local_address)
1299
+
1300
+ if remote_address:
1301
+ await trio_socket.connect(remote_address)
1302
+ return ConnectedUDPSocket(trio_socket)
1303
+ else:
1304
+ return UDPSocket(trio_socket)
1305
+
1306
+ @classmethod
1307
+ @overload
1308
+ async def create_unix_datagram_socket(
1309
+ cls, raw_socket: socket.socket, remote_path: None
1310
+ ) -> abc.UNIXDatagramSocket: ...
1311
+
1312
+ @classmethod
1313
+ @overload
1314
+ async def create_unix_datagram_socket(
1315
+ cls, raw_socket: socket.socket, remote_path: str | bytes
1316
+ ) -> abc.ConnectedUNIXDatagramSocket: ...
1317
+
1318
+ @classmethod
1319
+ async def create_unix_datagram_socket(
1320
+ cls, raw_socket: socket.socket, remote_path: str | bytes | None
1321
+ ) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket:
1322
+ trio_socket = trio.socket.from_stdlib_socket(raw_socket)
1323
+
1324
+ if remote_path:
1325
+ await trio_socket.connect(remote_path)
1326
+ return ConnectedUNIXDatagramSocket(trio_socket)
1327
+ else:
1328
+ return UNIXDatagramSocket(trio_socket)
1329
+
1330
+ @classmethod
1331
+ async def getaddrinfo(
1332
+ cls,
1333
+ host: bytes | str | None,
1334
+ port: str | int | None,
1335
+ *,
1336
+ family: int | AddressFamily = 0,
1337
+ type: int | SocketKind = 0,
1338
+ proto: int = 0,
1339
+ flags: int = 0,
1340
+ ) -> Sequence[
1341
+ tuple[
1342
+ AddressFamily,
1343
+ SocketKind,
1344
+ int,
1345
+ str,
1346
+ tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes],
1347
+ ]
1348
+ ]:
1349
+ return await trio.socket.getaddrinfo(host, port, family, type, proto, flags)
1350
+
1351
+ @classmethod
1352
+ async def getnameinfo(
1353
+ cls, sockaddr: IPSockAddrType, flags: int = 0
1354
+ ) -> tuple[str, str]:
1355
+ return await trio.socket.getnameinfo(sockaddr, flags)
1356
+
1357
+ @classmethod
1358
+ async def wait_readable(cls, obj: FileDescriptorLike) -> None:
1359
+ try:
1360
+ await wait_readable(obj)
1361
+ except trio.ClosedResourceError as exc:
1362
+ raise ClosedResourceError().with_traceback(exc.__traceback__) from None
1363
+ except trio.BusyResourceError:
1364
+ raise BusyResourceError("reading from") from None
1365
+
1366
+ @classmethod
1367
+ async def wait_writable(cls, obj: FileDescriptorLike) -> None:
1368
+ try:
1369
+ await wait_writable(obj)
1370
+ except trio.ClosedResourceError as exc:
1371
+ raise ClosedResourceError().with_traceback(exc.__traceback__) from None
1372
+ except trio.BusyResourceError:
1373
+ raise BusyResourceError("writing to") from None
1374
+
1375
+ @classmethod
1376
+ def notify_closing(cls, obj: FileDescriptorLike) -> None:
1377
+ notify_closing(obj)
1378
+
1379
+ @classmethod
1380
+ async def wrap_listener_socket(cls, sock: socket.socket) -> abc.SocketListener:
1381
+ if hasattr(socket, "AF_UNIX") and sock.family == socket.AF_UNIX:
1382
+ return UNIXSocketListener(sock)
1383
+
1384
+ return TCPSocketListener(sock)
1385
+
1386
+ @classmethod
1387
+ async def wrap_stream_socket(cls, sock: socket.socket) -> SocketStream:
1388
+ trio_sock = trio.socket.from_stdlib_socket(sock)
1389
+ return SocketStream(trio_sock)
1390
+
1391
+ @classmethod
1392
+ async def wrap_unix_stream_socket(cls, sock: socket.socket) -> UNIXSocketStream:
1393
+ trio_sock = trio.socket.from_stdlib_socket(sock)
1394
+ return UNIXSocketStream(trio_sock)
1395
+
1396
+ @classmethod
1397
+ async def wrap_udp_socket(cls, sock: socket.socket) -> UDPSocket:
1398
+ trio_sock = trio.socket.from_stdlib_socket(sock)
1399
+ return UDPSocket(trio_sock)
1400
+
1401
+ @classmethod
1402
+ async def wrap_connected_udp_socket(cls, sock: socket.socket) -> ConnectedUDPSocket:
1403
+ trio_sock = trio.socket.from_stdlib_socket(sock)
1404
+ return ConnectedUDPSocket(trio_sock)
1405
+
1406
+ @classmethod
1407
+ async def wrap_unix_datagram_socket(cls, sock: socket.socket) -> UNIXDatagramSocket:
1408
+ trio_sock = trio.socket.from_stdlib_socket(sock)
1409
+ return UNIXDatagramSocket(trio_sock)
1410
+
1411
+ @classmethod
1412
+ async def wrap_connected_unix_datagram_socket(
1413
+ cls, sock: socket.socket
1414
+ ) -> ConnectedUNIXDatagramSocket:
1415
+ trio_sock = trio.socket.from_stdlib_socket(sock)
1416
+ return ConnectedUNIXDatagramSocket(trio_sock)
1417
+
1418
+ @classmethod
1419
+ def current_default_thread_limiter(cls) -> CapacityLimiter:
1420
+ try:
1421
+ return _capacity_limiter_wrapper.get()
1422
+ except LookupError:
1423
+ limiter = CapacityLimiter(
1424
+ original=trio.to_thread.current_default_thread_limiter()
1425
+ )
1426
+ _capacity_limiter_wrapper.set(limiter)
1427
+ return limiter
1428
+
1429
+ @classmethod
1430
+ def open_signal_receiver(
1431
+ cls, *signals: Signals
1432
+ ) -> AbstractContextManager[AsyncIterator[Signals]]:
1433
+ return _SignalReceiver(signals)
1434
+
1435
+ @classmethod
1436
+ def get_current_task(cls) -> TaskInfo:
1437
+ task = current_task()
1438
+ return TrioTaskInfo(task)
1439
+
1440
+ @classmethod
1441
+ def get_running_tasks(cls) -> Sequence[TaskInfo]:
1442
+ root_task = current_root_task()
1443
+ assert root_task
1444
+ task_infos = [TrioTaskInfo(root_task)]
1445
+ nurseries = root_task.child_nurseries
1446
+ while nurseries:
1447
+ new_nurseries: list[trio.Nursery] = []
1448
+ for nursery in nurseries:
1449
+ for task in nursery.child_tasks:
1450
+ task_infos.append(TrioTaskInfo(task))
1451
+ new_nurseries.extend(task.child_nurseries)
1452
+
1453
+ nurseries = new_nurseries
1454
+
1455
+ return task_infos
1456
+
1457
+ @classmethod
1458
+ async def wait_all_tasks_blocked(cls) -> None:
1459
+ from trio.testing import wait_all_tasks_blocked
1460
+
1461
+ await wait_all_tasks_blocked()
1462
+
1463
+ @classmethod
1464
+ def create_test_runner(cls, options: dict[str, Any]) -> TestRunner:
1465
+ return TestRunner(**options)
1466
+
1467
+
1468
+ backend_class = TrioBackend
.venv/lib/python3.13/site-packages/anyio/_core/__init__.py ADDED
File without changes
.venv/lib/python3.13/site-packages/anyio/_core/_asyncio_selector_thread.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import socket
5
+ import threading
6
+ from collections.abc import Callable
7
+ from selectors import EVENT_READ, EVENT_WRITE, DefaultSelector
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ if TYPE_CHECKING:
11
+ from _typeshed import FileDescriptorLike
12
+
13
+ _selector_lock = threading.Lock()
14
+ _selector: Selector | None = None
15
+
16
+
17
+ class Selector:
18
+ def __init__(self) -> None:
19
+ self._thread = threading.Thread(target=self.run, name="AnyIO socket selector")
20
+ self._selector = DefaultSelector()
21
+ self._send, self._receive = socket.socketpair()
22
+ self._send.setblocking(False)
23
+ self._receive.setblocking(False)
24
+ # This somewhat reduces the amount of memory wasted queueing up data
25
+ # for wakeups. With these settings, maximum number of 1-byte sends
26
+ # before getting BlockingIOError:
27
+ # Linux 4.8: 6
28
+ # macOS (darwin 15.5): 1
29
+ # Windows 10: 525347
30
+ # Windows you're weird. (And on Windows setting SNDBUF to 0 makes send
31
+ # blocking, even on non-blocking sockets, so don't do that.)
32
+ self._receive.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1)
33
+ self._send.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1)
34
+ # On Windows this is a TCP socket so this might matter. On other
35
+ # platforms this fails b/c AF_UNIX sockets aren't actually TCP.
36
+ try:
37
+ self._send.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
38
+ except OSError:
39
+ pass
40
+
41
+ self._selector.register(self._receive, EVENT_READ)
42
+ self._closed = False
43
+
44
+ def start(self) -> None:
45
+ self._thread.start()
46
+ threading._register_atexit(self._stop) # type: ignore[attr-defined]
47
+
48
+ def _stop(self) -> None:
49
+ global _selector
50
+ self._closed = True
51
+ self._notify_self()
52
+ self._send.close()
53
+ self._thread.join()
54
+ self._selector.unregister(self._receive)
55
+ self._receive.close()
56
+ self._selector.close()
57
+ _selector = None
58
+ assert not self._selector.get_map(), (
59
+ "selector still has registered file descriptors after shutdown"
60
+ )
61
+
62
+ def _notify_self(self) -> None:
63
+ try:
64
+ self._send.send(b"\x00")
65
+ except BlockingIOError:
66
+ pass
67
+
68
+ def add_reader(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None:
69
+ loop = asyncio.get_running_loop()
70
+ try:
71
+ key = self._selector.get_key(fd)
72
+ except KeyError:
73
+ self._selector.register(fd, EVENT_READ, {EVENT_READ: (loop, callback)})
74
+ else:
75
+ if EVENT_READ in key.data:
76
+ raise ValueError(
77
+ "this file descriptor is already registered for reading"
78
+ )
79
+
80
+ key.data[EVENT_READ] = loop, callback
81
+ self._selector.modify(fd, key.events | EVENT_READ, key.data)
82
+
83
+ self._notify_self()
84
+
85
+ def add_writer(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None:
86
+ loop = asyncio.get_running_loop()
87
+ try:
88
+ key = self._selector.get_key(fd)
89
+ except KeyError:
90
+ self._selector.register(fd, EVENT_WRITE, {EVENT_WRITE: (loop, callback)})
91
+ else:
92
+ if EVENT_WRITE in key.data:
93
+ raise ValueError(
94
+ "this file descriptor is already registered for writing"
95
+ )
96
+
97
+ key.data[EVENT_WRITE] = loop, callback
98
+ self._selector.modify(fd, key.events | EVENT_WRITE, key.data)
99
+
100
+ self._notify_self()
101
+
102
+ def remove_reader(self, fd: FileDescriptorLike) -> bool:
103
+ try:
104
+ key = self._selector.get_key(fd)
105
+ except KeyError:
106
+ return False
107
+
108
+ if new_events := key.events ^ EVENT_READ:
109
+ del key.data[EVENT_READ]
110
+ self._selector.modify(fd, new_events, key.data)
111
+ else:
112
+ self._selector.unregister(fd)
113
+
114
+ return True
115
+
116
+ def remove_writer(self, fd: FileDescriptorLike) -> bool:
117
+ try:
118
+ key = self._selector.get_key(fd)
119
+ except KeyError:
120
+ return False
121
+
122
+ if new_events := key.events ^ EVENT_WRITE:
123
+ del key.data[EVENT_WRITE]
124
+ self._selector.modify(fd, new_events, key.data)
125
+ else:
126
+ self._selector.unregister(fd)
127
+
128
+ return True
129
+
130
+ def run(self) -> None:
131
+ while not self._closed:
132
+ for key, events in self._selector.select():
133
+ if key.fileobj is self._receive:
134
+ try:
135
+ while self._receive.recv(4096):
136
+ pass
137
+ except BlockingIOError:
138
+ pass
139
+
140
+ continue
141
+
142
+ if events & EVENT_READ:
143
+ loop, callback = key.data[EVENT_READ]
144
+ self.remove_reader(key.fd)
145
+ try:
146
+ loop.call_soon_threadsafe(callback)
147
+ except RuntimeError:
148
+ pass # the loop was already closed
149
+
150
+ if events & EVENT_WRITE:
151
+ loop, callback = key.data[EVENT_WRITE]
152
+ self.remove_writer(key.fd)
153
+ try:
154
+ loop.call_soon_threadsafe(callback)
155
+ except RuntimeError:
156
+ pass # the loop was already closed
157
+
158
+
159
+ def get_selector() -> Selector:
160
+ global _selector
161
+
162
+ with _selector_lock:
163
+ if _selector is None:
164
+ _selector = Selector()
165
+ _selector.start()
166
+
167
+ return _selector
.venv/lib/python3.13/site-packages/anyio/_core/_contextmanagers.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from abc import abstractmethod
4
+ from contextlib import AbstractAsyncContextManager, AbstractContextManager
5
+ from inspect import isasyncgen, iscoroutine, isgenerator
6
+ from types import TracebackType
7
+ from typing import Protocol, TypeVar, cast, final
8
+
9
+ _T_co = TypeVar("_T_co", covariant=True)
10
+ _ExitT_co = TypeVar("_ExitT_co", covariant=True, bound="bool | None")
11
+
12
+
13
+ class _SupportsCtxMgr(Protocol[_T_co, _ExitT_co]):
14
+ def __contextmanager__(self) -> AbstractContextManager[_T_co, _ExitT_co]: ...
15
+
16
+
17
+ class _SupportsAsyncCtxMgr(Protocol[_T_co, _ExitT_co]):
18
+ def __asynccontextmanager__(
19
+ self,
20
+ ) -> AbstractAsyncContextManager[_T_co, _ExitT_co]: ...
21
+
22
+
23
+ class ContextManagerMixin:
24
+ """
25
+ Mixin class providing context manager functionality via a generator-based
26
+ implementation.
27
+
28
+ This class allows you to implement a context manager via :meth:`__contextmanager__`
29
+ which should return a generator. The mechanics are meant to mirror those of
30
+ :func:`@contextmanager <contextlib.contextmanager>`.
31
+
32
+ .. note:: Classes using this mix-in are not reentrant as context managers, meaning
33
+ that once you enter it, you can't re-enter before first exiting it.
34
+
35
+ .. seealso:: :doc:`contextmanagers`
36
+ """
37
+
38
+ __cm: AbstractContextManager[object, bool | None] | None = None
39
+
40
+ @final
41
+ def __enter__(self: _SupportsCtxMgr[_T_co, bool | None]) -> _T_co:
42
+ # Needed for mypy to assume self still has the __cm member
43
+ assert isinstance(self, ContextManagerMixin)
44
+ if self.__cm is not None:
45
+ raise RuntimeError(
46
+ f"this {self.__class__.__qualname__} has already been entered"
47
+ )
48
+
49
+ cm = self.__contextmanager__()
50
+ if not isinstance(cm, AbstractContextManager):
51
+ if isgenerator(cm):
52
+ raise TypeError(
53
+ "__contextmanager__() returned a generator object instead of "
54
+ "a context manager. Did you forget to add the @contextmanager "
55
+ "decorator?"
56
+ )
57
+
58
+ raise TypeError(
59
+ f"__contextmanager__() did not return a context manager object, "
60
+ f"but {cm.__class__!r}"
61
+ )
62
+
63
+ if cm is self:
64
+ raise TypeError(
65
+ f"{self.__class__.__qualname__}.__contextmanager__() returned "
66
+ f"self. Did you forget to add the @contextmanager decorator and a "
67
+ f"'yield' statement?"
68
+ )
69
+
70
+ value = cm.__enter__()
71
+ self.__cm = cm
72
+ return value
73
+
74
+ @final
75
+ def __exit__(
76
+ self: _SupportsCtxMgr[object, _ExitT_co],
77
+ exc_type: type[BaseException] | None,
78
+ exc_val: BaseException | None,
79
+ exc_tb: TracebackType | None,
80
+ ) -> _ExitT_co:
81
+ # Needed for mypy to assume self still has the __cm member
82
+ assert isinstance(self, ContextManagerMixin)
83
+ if self.__cm is None:
84
+ raise RuntimeError(
85
+ f"this {self.__class__.__qualname__} has not been entered yet"
86
+ )
87
+
88
+ # Prevent circular references
89
+ cm = self.__cm
90
+ del self.__cm
91
+
92
+ return cast(_ExitT_co, cm.__exit__(exc_type, exc_val, exc_tb))
93
+
94
+ @abstractmethod
95
+ def __contextmanager__(self) -> AbstractContextManager[object, bool | None]:
96
+ """
97
+ Implement your context manager logic here.
98
+
99
+ This method **must** be decorated with
100
+ :func:`@contextmanager <contextlib.contextmanager>`.
101
+
102
+ .. note:: Remember that the ``yield`` will raise any exception raised in the
103
+ enclosed context block, so use a ``finally:`` block to clean up resources!
104
+
105
+ :return: a context manager object
106
+ """
107
+
108
+
109
+ class AsyncContextManagerMixin:
110
+ """
111
+ Mixin class providing async context manager functionality via a generator-based
112
+ implementation.
113
+
114
+ This class allows you to implement a context manager via
115
+ :meth:`__asynccontextmanager__`. The mechanics are meant to mirror those of
116
+ :func:`@asynccontextmanager <contextlib.asynccontextmanager>`.
117
+
118
+ .. note:: Classes using this mix-in are not reentrant as context managers, meaning
119
+ that once you enter it, you can't re-enter before first exiting it.
120
+
121
+ .. seealso:: :doc:`contextmanagers`
122
+ """
123
+
124
+ __cm: AbstractAsyncContextManager[object, bool | None] | None = None
125
+
126
+ @final
127
+ async def __aenter__(self: _SupportsAsyncCtxMgr[_T_co, bool | None]) -> _T_co:
128
+ # Needed for mypy to assume self still has the __cm member
129
+ assert isinstance(self, AsyncContextManagerMixin)
130
+ if self.__cm is not None:
131
+ raise RuntimeError(
132
+ f"this {self.__class__.__qualname__} has already been entered"
133
+ )
134
+
135
+ cm = self.__asynccontextmanager__()
136
+ if not isinstance(cm, AbstractAsyncContextManager):
137
+ if isasyncgen(cm):
138
+ raise TypeError(
139
+ "__asynccontextmanager__() returned an async generator instead of "
140
+ "an async context manager. Did you forget to add the "
141
+ "@asynccontextmanager decorator?"
142
+ )
143
+ elif iscoroutine(cm):
144
+ cm.close()
145
+ raise TypeError(
146
+ "__asynccontextmanager__() returned a coroutine object instead of "
147
+ "an async context manager. Did you forget to add the "
148
+ "@asynccontextmanager decorator and a 'yield' statement?"
149
+ )
150
+
151
+ raise TypeError(
152
+ f"__asynccontextmanager__() did not return an async context manager, "
153
+ f"but {cm.__class__!r}"
154
+ )
155
+
156
+ if cm is self:
157
+ raise TypeError(
158
+ f"{self.__class__.__qualname__}.__asynccontextmanager__() returned "
159
+ f"self. Did you forget to add the @asynccontextmanager decorator and a "
160
+ f"'yield' statement?"
161
+ )
162
+
163
+ value = await cm.__aenter__()
164
+ self.__cm = cm
165
+ return value
166
+
167
+ @final
168
+ async def __aexit__(
169
+ self: _SupportsAsyncCtxMgr[object, _ExitT_co],
170
+ exc_type: type[BaseException] | None,
171
+ exc_val: BaseException | None,
172
+ exc_tb: TracebackType | None,
173
+ ) -> _ExitT_co:
174
+ assert isinstance(self, AsyncContextManagerMixin)
175
+ if self.__cm is None:
176
+ raise RuntimeError(
177
+ f"this {self.__class__.__qualname__} has not been entered yet"
178
+ )
179
+
180
+ # Prevent circular references
181
+ cm = self.__cm
182
+ del self.__cm
183
+
184
+ return cast(_ExitT_co, await cm.__aexit__(exc_type, exc_val, exc_tb))
185
+
186
+ @abstractmethod
187
+ def __asynccontextmanager__(
188
+ self,
189
+ ) -> AbstractAsyncContextManager[object, bool | None]:
190
+ """
191
+ Implement your async context manager logic here.
192
+
193
+ This method **must** be decorated with
194
+ :func:`@asynccontextmanager <contextlib.asynccontextmanager>`.
195
+
196
+ .. note:: Remember that the ``yield`` will raise any exception raised in the
197
+ enclosed context block, so use a ``finally:`` block to clean up resources!
198
+
199
+ :return: an async context manager object
200
+ """
.venv/lib/python3.13/site-packages/anyio/_core/_eventloop.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import sys
5
+ import threading
6
+ from collections.abc import Awaitable, Callable, Generator
7
+ from contextlib import contextmanager
8
+ from contextvars import Token
9
+ from importlib import import_module
10
+ from typing import TYPE_CHECKING, Any, TypeVar
11
+
12
+ from ._exceptions import NoEventLoopError
13
+
14
+ if sys.version_info >= (3, 11):
15
+ from typing import TypeVarTuple, Unpack
16
+ else:
17
+ from typing_extensions import TypeVarTuple, Unpack
18
+
19
+ sniffio: Any
20
+ try:
21
+ import sniffio
22
+ except ModuleNotFoundError:
23
+ sniffio = None
24
+
25
+ if TYPE_CHECKING:
26
+ from ..abc import AsyncBackend
27
+
28
+ # This must be updated when new backends are introduced
29
+ BACKENDS = "asyncio", "trio"
30
+
31
+ T_Retval = TypeVar("T_Retval")
32
+ PosArgsT = TypeVarTuple("PosArgsT")
33
+
34
+ threadlocals = threading.local()
35
+ loaded_backends: dict[str, type[AsyncBackend]] = {}
36
+
37
+
38
+ def run(
39
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
40
+ *args: Unpack[PosArgsT],
41
+ backend: str = "asyncio",
42
+ backend_options: dict[str, Any] | None = None,
43
+ ) -> T_Retval:
44
+ """
45
+ Run the given coroutine function in an asynchronous event loop.
46
+
47
+ The current thread must not be already running an event loop.
48
+
49
+ :param func: a coroutine function
50
+ :param args: positional arguments to ``func``
51
+ :param backend: name of the asynchronous event loop implementation – currently
52
+ either ``asyncio`` or ``trio``
53
+ :param backend_options: keyword arguments to call the backend ``run()``
54
+ implementation with (documented :ref:`here <backend options>`)
55
+ :return: the return value of the coroutine function
56
+ :raises RuntimeError: if an asynchronous event loop is already running in this
57
+ thread
58
+ :raises LookupError: if the named backend is not found
59
+
60
+ """
61
+ if asynclib_name := current_async_library():
62
+ raise RuntimeError(f"Already running {asynclib_name} in this thread")
63
+
64
+ try:
65
+ async_backend = get_async_backend(backend)
66
+ except ImportError as exc:
67
+ if backend in BACKENDS:
68
+ raise LookupError(
69
+ f"Backend {backend!r} is not available. "
70
+ f"Install it with: pip install anyio[{backend}]"
71
+ ) from exc
72
+
73
+ raise LookupError(f"No such backend: {backend}") from exc
74
+
75
+ token = None
76
+ if asynclib_name is None:
77
+ # Since we're in control of the event loop, we can cache the name of the async
78
+ # library
79
+ token = set_current_async_library(backend)
80
+
81
+ try:
82
+ backend_options = backend_options or {}
83
+ return async_backend.run(func, args, {}, backend_options)
84
+ finally:
85
+ reset_current_async_library(token)
86
+
87
+
88
+ async def sleep(delay: float) -> None:
89
+ """
90
+ Pause the current task for the specified duration.
91
+
92
+ :param delay: the duration, in seconds
93
+
94
+ """
95
+ return await get_async_backend().sleep(delay)
96
+
97
+
98
+ async def sleep_forever() -> None:
99
+ """
100
+ Pause the current task until it's cancelled.
101
+
102
+ This is a shortcut for ``sleep(math.inf)``.
103
+
104
+ .. versionadded:: 3.1
105
+
106
+ """
107
+ await sleep(math.inf)
108
+
109
+
110
+ async def sleep_until(deadline: float) -> None:
111
+ """
112
+ Pause the current task until the given time.
113
+
114
+ :param deadline: the absolute time to wake up at (according to the internal
115
+ monotonic clock of the event loop)
116
+
117
+ .. versionadded:: 3.1
118
+
119
+ """
120
+ now = current_time()
121
+ await sleep(max(deadline - now, 0))
122
+
123
+
124
+ def current_time() -> float:
125
+ """
126
+ Return the current value of the event loop's internal clock.
127
+
128
+ :return: the clock value (seconds)
129
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
130
+ current thread
131
+
132
+ """
133
+ return get_async_backend().current_time()
134
+
135
+
136
+ def get_all_backends() -> tuple[str, ...]:
137
+ """Return a tuple of the names of all built-in backends."""
138
+ return BACKENDS
139
+
140
+
141
+ def get_available_backends() -> tuple[str, ...]:
142
+ """
143
+ Test for the availability of built-in backends.
144
+
145
+ :return a tuple of the built-in backend names that were successfully imported
146
+
147
+ .. versionadded:: 4.12
148
+
149
+ """
150
+ available_backends: list[str] = []
151
+ for backend_name in get_all_backends():
152
+ try:
153
+ get_async_backend(backend_name)
154
+ except ImportError:
155
+ continue
156
+
157
+ available_backends.append(backend_name)
158
+
159
+ return tuple(available_backends)
160
+
161
+
162
+ def get_cancelled_exc_class() -> type[BaseException]:
163
+ """
164
+ Return the current async library's cancellation exception class.
165
+
166
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
167
+ current thread
168
+
169
+ """
170
+ return get_async_backend().cancelled_exception_class()
171
+
172
+
173
+ #
174
+ # Private API
175
+ #
176
+
177
+
178
+ @contextmanager
179
+ def claim_worker_thread(
180
+ backend_class: type[AsyncBackend], token: object
181
+ ) -> Generator[Any, None, None]:
182
+ from ..lowlevel import EventLoopToken
183
+
184
+ threadlocals.current_token = EventLoopToken(backend_class, token)
185
+ try:
186
+ yield
187
+ finally:
188
+ del threadlocals.current_token
189
+
190
+
191
+ def get_async_backend(asynclib_name: str | None = None) -> type[AsyncBackend]:
192
+ if asynclib_name is None:
193
+ asynclib_name = current_async_library()
194
+ if not asynclib_name:
195
+ raise NoEventLoopError(
196
+ f"Not currently running on any asynchronous event loop. "
197
+ f"Available async backends: {', '.join(get_all_backends())}"
198
+ )
199
+
200
+ # We use our own dict instead of sys.modules to get the already imported back-end
201
+ # class because the appropriate modules in sys.modules could potentially be only
202
+ # partially initialized
203
+ try:
204
+ return loaded_backends[asynclib_name]
205
+ except KeyError:
206
+ module = import_module(f"anyio._backends._{asynclib_name}")
207
+ loaded_backends[asynclib_name] = module.backend_class
208
+ return module.backend_class
209
+
210
+
211
+ def current_async_library() -> str | None:
212
+ if sniffio is None:
213
+ # If sniffio is not installed, we assume we're either running asyncio or nothing
214
+ import asyncio
215
+
216
+ try:
217
+ asyncio.get_running_loop()
218
+ return "asyncio"
219
+ except RuntimeError:
220
+ pass
221
+ else:
222
+ try:
223
+ return sniffio.current_async_library()
224
+ except sniffio.AsyncLibraryNotFoundError:
225
+ pass
226
+
227
+ return None
228
+
229
+
230
+ def set_current_async_library(asynclib_name: str | None) -> Token | None:
231
+ # no-op if sniffio is not installed
232
+ if sniffio is None:
233
+ return None
234
+
235
+ return sniffio.current_async_library_cvar.set(asynclib_name)
236
+
237
+
238
+ def reset_current_async_library(token: Token | None) -> None:
239
+ if token is not None:
240
+ sniffio.current_async_library_cvar.reset(token)
.venv/lib/python3.13/site-packages/anyio/_core/_exceptions.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from collections.abc import Generator
5
+ from textwrap import dedent
6
+ from typing import Any
7
+
8
+ if sys.version_info < (3, 11):
9
+ from exceptiongroup import BaseExceptionGroup
10
+
11
+
12
+ class BrokenResourceError(Exception):
13
+ """
14
+ Raised when trying to use a resource that has been rendered unusable due to external
15
+ causes (e.g. a send stream whose peer has disconnected).
16
+ """
17
+
18
+
19
+ class BrokenWorkerProcess(Exception):
20
+ """
21
+ Raised by :meth:`~anyio.to_process.run_sync` if the worker process terminates abruptly or
22
+ otherwise misbehaves.
23
+ """
24
+
25
+
26
+ class BrokenWorkerInterpreter(Exception):
27
+ """
28
+ Raised by :meth:`~anyio.to_interpreter.run_sync` if an unexpected exception is
29
+ raised in the subinterpreter.
30
+ """
31
+
32
+ def __init__(self, excinfo: Any):
33
+ # This was adapted from concurrent.futures.interpreter.ExecutionFailed
34
+ msg = excinfo.formatted
35
+ if not msg:
36
+ if excinfo.type and excinfo.msg:
37
+ msg = f"{excinfo.type.__name__}: {excinfo.msg}"
38
+ else:
39
+ msg = excinfo.type.__name__ or excinfo.msg
40
+
41
+ super().__init__(msg)
42
+ self.excinfo = excinfo
43
+
44
+ def __str__(self) -> str:
45
+ try:
46
+ formatted = self.excinfo.errdisplay
47
+ except Exception:
48
+ return super().__str__()
49
+ else:
50
+ return dedent(
51
+ f"""
52
+ {super().__str__()}
53
+
54
+ Uncaught in the interpreter:
55
+
56
+ {formatted}
57
+ """.strip()
58
+ )
59
+
60
+
61
+ class BusyResourceError(Exception):
62
+ """
63
+ Raised when two tasks are trying to read from or write to the same resource
64
+ concurrently.
65
+ """
66
+
67
+ def __init__(self, action: str):
68
+ super().__init__(f"Another task is already {action} this resource")
69
+
70
+
71
+ class ClosedResourceError(Exception):
72
+ """Raised when trying to use a resource that has been closed."""
73
+
74
+
75
+ class ConnectionFailed(OSError):
76
+ """
77
+ Raised when a connection attempt fails.
78
+
79
+ .. note:: This class inherits from :exc:`OSError` for backwards compatibility.
80
+ """
81
+
82
+
83
+ def iterate_exceptions(
84
+ exception: BaseException,
85
+ ) -> Generator[BaseException, None, None]:
86
+ if isinstance(exception, BaseExceptionGroup):
87
+ for exc in exception.exceptions:
88
+ yield from iterate_exceptions(exc)
89
+ else:
90
+ yield exception
91
+
92
+
93
+ class DelimiterNotFound(Exception):
94
+ """
95
+ Raised during
96
+ :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the
97
+ maximum number of bytes has been read without the delimiter being found.
98
+ """
99
+
100
+ def __init__(self, max_bytes: int) -> None:
101
+ super().__init__(
102
+ f"The delimiter was not found among the first {max_bytes} bytes"
103
+ )
104
+
105
+
106
+ class EndOfStream(Exception):
107
+ """
108
+ Raised when trying to read from a stream that has been closed from the other end.
109
+ """
110
+
111
+
112
+ class IncompleteRead(Exception):
113
+ """
114
+ Raised during
115
+ :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_exactly` or
116
+ :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the
117
+ connection is closed before the requested amount of bytes has been read.
118
+ """
119
+
120
+ def __init__(self) -> None:
121
+ super().__init__(
122
+ "The stream was closed before the read operation could be completed"
123
+ )
124
+
125
+
126
+ class TypedAttributeLookupError(LookupError):
127
+ """
128
+ Raised by :meth:`~anyio.TypedAttributeProvider.extra` when the given typed attribute
129
+ is not found and no default value has been given.
130
+ """
131
+
132
+
133
+ class WouldBlock(Exception):
134
+ """Raised by ``X_nowait`` functions if ``X()`` would block."""
135
+
136
+
137
+ class NoEventLoopError(RuntimeError):
138
+ """
139
+ Raised by several functions that require an event loop to be running in the current
140
+ thread when there is no running event loop.
141
+
142
+ This is also raised by :func:`.from_thread.run` and :func:`.from_thread.run_sync`
143
+ if not calling from an AnyIO worker thread, and no ``token`` was passed.
144
+ """
145
+
146
+
147
+ class RunFinishedError(RuntimeError):
148
+ """
149
+ Raised by :func:`.from_thread.run` and :func:`.from_thread.run_sync` if the event
150
+ loop associated with the explicitly passed token has already finished.
151
+ """
152
+
153
+ def __init__(self) -> None:
154
+ super().__init__(
155
+ "The event loop associated with the given token has already finished"
156
+ )
157
+
158
+
159
+ class TaskFailed(Exception):
160
+ """
161
+ Raised when awaiting on, or attempting to access the return value of, a
162
+ :class:`.TaskHandle` that raised an exception.
163
+ """
164
+
165
+
166
+ class TaskCancelled(TaskFailed):
167
+ """
168
+ Raised when awaiting on, or attempting to access the return value of, a
169
+ :class:`.TaskHandle` that was cancelled.
170
+ """
171
+
172
+
173
+ class TaskNotFinished(Exception):
174
+ """
175
+ Raised when attempting to access the return value or exception of a
176
+ :class:`.TaskHandle` that is still pending completion.
177
+ """
.venv/lib/python3.13/site-packages/anyio/_core/_fileio.py ADDED
@@ -0,0 +1,960 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import pathlib
5
+ import sys
6
+ from collections.abc import (
7
+ AsyncIterator,
8
+ Callable,
9
+ Iterable,
10
+ Iterator,
11
+ Sequence,
12
+ )
13
+ from dataclasses import dataclass
14
+ from functools import partial
15
+ from os import PathLike
16
+ from typing import (
17
+ IO,
18
+ TYPE_CHECKING,
19
+ Any,
20
+ AnyStr,
21
+ ClassVar,
22
+ Final,
23
+ Generic,
24
+ TypeVar,
25
+ overload,
26
+ )
27
+
28
+ from .. import to_thread
29
+ from ..abc import AsyncResource
30
+ from ._synchronization import CapacityLimiter
31
+
32
+ if sys.version_info >= (3, 11):
33
+ from typing import Self
34
+ else:
35
+ from typing_extensions import Self
36
+
37
+ if sys.version_info >= (3, 14):
38
+ from pathlib.types import PathInfo
39
+
40
+ if TYPE_CHECKING:
41
+ from types import ModuleType
42
+
43
+ from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer
44
+ else:
45
+ ReadableBuffer = OpenBinaryMode = OpenTextMode = WriteableBuffer = object
46
+
47
+
48
+ T = TypeVar("T", bound="Path")
49
+
50
+
51
+ class AsyncFile(AsyncResource, Generic[AnyStr]):
52
+ """
53
+ An asynchronous file object.
54
+
55
+ This class wraps a standard file object and provides async friendly versions of the
56
+ following blocking methods (where available on the original file object):
57
+
58
+ * read
59
+ * read1
60
+ * readline
61
+ * readlines
62
+ * readinto
63
+ * readinto1
64
+ * write
65
+ * writelines
66
+ * truncate
67
+ * seek
68
+ * tell
69
+ * flush
70
+
71
+ All other methods are directly passed through.
72
+
73
+ This class supports the asynchronous context manager protocol which closes the
74
+ underlying file at the end of the context block.
75
+
76
+ This class also supports asynchronous iteration::
77
+
78
+ async with await open_file(...) as f:
79
+ async for line in f:
80
+ print(line)
81
+ """
82
+
83
+ def __init__(
84
+ self, fp: IO[AnyStr], *, limiter: CapacityLimiter | None = None
85
+ ) -> None:
86
+ if limiter is not None and not isinstance(limiter, CapacityLimiter):
87
+ raise TypeError(
88
+ f"limiter must be a CapacityLimiter or None, not "
89
+ f"{limiter.__class__.__name__}"
90
+ )
91
+
92
+ self._fp: Any = fp
93
+ self._limiter = limiter
94
+
95
+ def __getattr__(self, name: str) -> object:
96
+ return getattr(self._fp, name)
97
+
98
+ @property
99
+ def limiter(self) -> CapacityLimiter | None:
100
+ """The capacity limiter used by this file object, if not the global limiter."""
101
+ return self._limiter
102
+
103
+ @property
104
+ def wrapped(self) -> IO[AnyStr]:
105
+ """The wrapped file object."""
106
+ return self._fp
107
+
108
+ async def __aiter__(self) -> AsyncIterator[AnyStr]:
109
+ while True:
110
+ line = await self.readline()
111
+ if line:
112
+ yield line
113
+ else:
114
+ break
115
+
116
+ async def aclose(self) -> None:
117
+ return await to_thread.run_sync(self._fp.close, limiter=self._limiter)
118
+
119
+ async def read(self, size: int = -1) -> AnyStr:
120
+ return await to_thread.run_sync(self._fp.read, size, limiter=self._limiter)
121
+
122
+ async def read1(self: AsyncFile[bytes], size: int = -1) -> bytes:
123
+ return await to_thread.run_sync(self._fp.read1, size, limiter=self._limiter)
124
+
125
+ async def readline(self) -> AnyStr:
126
+ return await to_thread.run_sync(self._fp.readline, limiter=self._limiter)
127
+
128
+ async def readlines(self) -> list[AnyStr]:
129
+ return await to_thread.run_sync(self._fp.readlines, limiter=self._limiter)
130
+
131
+ async def readinto(self: AsyncFile[bytes], b: WriteableBuffer) -> int:
132
+ return await to_thread.run_sync(self._fp.readinto, b, limiter=self._limiter)
133
+
134
+ async def readinto1(self: AsyncFile[bytes], b: WriteableBuffer) -> int:
135
+ return await to_thread.run_sync(self._fp.readinto1, b, limiter=self._limiter)
136
+
137
+ @overload
138
+ async def write(self: AsyncFile[bytes], b: ReadableBuffer) -> int: ...
139
+
140
+ @overload
141
+ async def write(self: AsyncFile[str], b: str) -> int: ...
142
+
143
+ async def write(self, b: ReadableBuffer | str) -> int:
144
+ return await to_thread.run_sync(self._fp.write, b, limiter=self._limiter)
145
+
146
+ @overload
147
+ async def writelines(
148
+ self: AsyncFile[bytes], lines: Iterable[ReadableBuffer]
149
+ ) -> None: ...
150
+
151
+ @overload
152
+ async def writelines(self: AsyncFile[str], lines: Iterable[str]) -> None: ...
153
+
154
+ async def writelines(self, lines: Iterable[ReadableBuffer] | Iterable[str]) -> None:
155
+ return await to_thread.run_sync(
156
+ self._fp.writelines, lines, limiter=self._limiter
157
+ )
158
+
159
+ async def truncate(self, size: int | None = None) -> int:
160
+ return await to_thread.run_sync(self._fp.truncate, size, limiter=self._limiter)
161
+
162
+ async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int:
163
+ return await to_thread.run_sync(
164
+ self._fp.seek, offset, whence, limiter=self._limiter
165
+ )
166
+
167
+ async def tell(self) -> int:
168
+ return await to_thread.run_sync(self._fp.tell, limiter=self._limiter)
169
+
170
+ async def flush(self) -> None:
171
+ return await to_thread.run_sync(self._fp.flush, limiter=self._limiter)
172
+
173
+
174
+ @overload
175
+ async def open_file(
176
+ file: str | PathLike[str] | int,
177
+ mode: OpenBinaryMode,
178
+ buffering: int = ...,
179
+ encoding: str | None = ...,
180
+ errors: str | None = ...,
181
+ newline: str | None = ...,
182
+ closefd: bool = ...,
183
+ opener: Callable[[str, int], int] | None = ...,
184
+ *,
185
+ limiter: CapacityLimiter | None = ...,
186
+ ) -> AsyncFile[bytes]: ...
187
+
188
+
189
+ @overload
190
+ async def open_file(
191
+ file: str | PathLike[str] | int,
192
+ mode: OpenTextMode = ...,
193
+ buffering: int = ...,
194
+ encoding: str | None = ...,
195
+ errors: str | None = ...,
196
+ newline: str | None = ...,
197
+ closefd: bool = ...,
198
+ opener: Callable[[str, int], int] | None = ...,
199
+ *,
200
+ limiter: CapacityLimiter | None = ...,
201
+ ) -> AsyncFile[str]: ...
202
+
203
+
204
+ async def open_file(
205
+ file: str | PathLike[str] | int,
206
+ mode: str = "r",
207
+ buffering: int = -1,
208
+ encoding: str | None = None,
209
+ errors: str | None = None,
210
+ newline: str | None = None,
211
+ closefd: bool = True,
212
+ opener: Callable[[str, int], int] | None = None,
213
+ *,
214
+ limiter: CapacityLimiter | None = None,
215
+ ) -> AsyncFile[Any]:
216
+ """
217
+ Open a file asynchronously.
218
+
219
+ Except for ``limiter``, the arguments are exactly the same as for the builtin :func:`open`.
220
+
221
+ :param limiter: an optional capacity limiter to use with the file
222
+ instead of the default one
223
+ :return: an asynchronous file object
224
+
225
+ .. versionchanged:: 4.14.0
226
+ Added the ``limiter`` keyword argument.
227
+
228
+ """
229
+ fp = await to_thread.run_sync(
230
+ open,
231
+ file,
232
+ mode,
233
+ buffering,
234
+ encoding,
235
+ errors,
236
+ newline,
237
+ closefd,
238
+ opener,
239
+ limiter=limiter,
240
+ )
241
+ return AsyncFile(fp, limiter=limiter)
242
+
243
+
244
+ def wrap_file(
245
+ file: IO[AnyStr], *, limiter: CapacityLimiter | None = None
246
+ ) -> AsyncFile[AnyStr]:
247
+ """
248
+ Wrap an existing file as an asynchronous file.
249
+
250
+ :param file: an existing file-like object
251
+ :param limiter: an optional capacity limiter to use with the file
252
+ instead of the default one
253
+ :return: an asynchronous file object
254
+
255
+ .. versionchanged:: 4.14.0
256
+ Added the ``limiter`` keyword argument.
257
+
258
+ """
259
+ return AsyncFile(file, limiter=limiter)
260
+
261
+
262
+ @dataclass(eq=False)
263
+ class _PathIterator(AsyncIterator[T]):
264
+ iterator: Iterator[PathLike[str]]
265
+ limiter: CapacityLimiter | None
266
+ # This was added to ensure that iterating over a subclass of Path yields instances
267
+ # of that subclass rather than the base Path class.
268
+ path_cls: type[T]
269
+
270
+ async def __anext__(self) -> T:
271
+ nextval = await to_thread.run_sync(
272
+ next, self.iterator, None, abandon_on_cancel=True, limiter=self.limiter
273
+ )
274
+ if nextval is None:
275
+ raise StopAsyncIteration from None
276
+
277
+ return self.path_cls(nextval, limiter=self.limiter)
278
+
279
+
280
+ class Path:
281
+ """
282
+ An asynchronous version of :class:`pathlib.Path`.
283
+
284
+ This class cannot be substituted for :class:`pathlib.Path` or
285
+ :class:`pathlib.PurePath`, but it is compatible with the :class:`os.PathLike`
286
+ interface.
287
+
288
+ It implements the Python 3.10 version of :class:`pathlib.Path` interface, except for
289
+ the deprecated :meth:`~pathlib.Path.link_to` method.
290
+
291
+ Some methods may be unavailable or have limited functionality, based on the Python
292
+ version:
293
+
294
+ * :meth:`~pathlib.Path.copy` (available on Python 3.14 or later)
295
+ * :meth:`~pathlib.Path.copy_into` (available on Python 3.14 or later)
296
+ * :meth:`~pathlib.Path.from_uri` (available on Python 3.13 or later)
297
+ * :meth:`~pathlib.PurePath.full_match` (available on Python 3.13 or later)
298
+ * :attr:`~pathlib.Path.info` (available on Python 3.14 or later)
299
+ * :meth:`~pathlib.Path.is_junction` (available on Python 3.12 or later)
300
+ * :meth:`~pathlib.PurePath.match` (the ``case_sensitive`` parameter is only
301
+ available on Python 3.13 or later)
302
+ * :meth:`~pathlib.Path.move` (available on Python 3.14 or later)
303
+ * :meth:`~pathlib.Path.move_into` (available on Python 3.14 or later)
304
+ * :meth:`~pathlib.PurePath.relative_to` (the ``walk_up`` parameter is only available
305
+ on Python 3.12 or later)
306
+ * :meth:`~pathlib.Path.walk` (available on Python 3.12 or later)
307
+
308
+ Any methods that do disk I/O need to be awaited on. These methods are:
309
+
310
+ * :meth:`~pathlib.Path.absolute`
311
+ * :meth:`~pathlib.Path.chmod`
312
+ * :meth:`~pathlib.Path.cwd`
313
+ * :meth:`~pathlib.Path.exists`
314
+ * :meth:`~pathlib.Path.expanduser`
315
+ * :meth:`~pathlib.Path.group`
316
+ * :meth:`~pathlib.Path.hardlink_to`
317
+ * :meth:`~pathlib.Path.home`
318
+ * :meth:`~pathlib.Path.is_block_device`
319
+ * :meth:`~pathlib.Path.is_char_device`
320
+ * :meth:`~pathlib.Path.is_dir`
321
+ * :meth:`~pathlib.Path.is_fifo`
322
+ * :meth:`~pathlib.Path.is_file`
323
+ * :meth:`~pathlib.Path.is_junction`
324
+ * :meth:`~pathlib.Path.is_mount`
325
+ * :meth:`~pathlib.Path.is_socket`
326
+ * :meth:`~pathlib.Path.is_symlink`
327
+ * :meth:`~pathlib.Path.lchmod`
328
+ * :meth:`~pathlib.Path.lstat`
329
+ * :meth:`~pathlib.Path.mkdir`
330
+ * :meth:`~pathlib.Path.open`
331
+ * :meth:`~pathlib.Path.owner`
332
+ * :meth:`~pathlib.Path.read_bytes`
333
+ * :meth:`~pathlib.Path.read_text`
334
+ * :meth:`~pathlib.Path.readlink`
335
+ * :meth:`~pathlib.Path.rename`
336
+ * :meth:`~pathlib.Path.replace`
337
+ * :meth:`~pathlib.Path.resolve`
338
+ * :meth:`~pathlib.Path.rmdir`
339
+ * :meth:`~pathlib.Path.samefile`
340
+ * :meth:`~pathlib.Path.stat`
341
+ * :meth:`~pathlib.Path.symlink_to`
342
+ * :meth:`~pathlib.Path.touch`
343
+ * :meth:`~pathlib.Path.unlink`
344
+ * :meth:`~pathlib.Path.walk`
345
+ * :meth:`~pathlib.Path.write_bytes`
346
+ * :meth:`~pathlib.Path.write_text`
347
+
348
+ Additionally, the following methods return an async iterator yielding
349
+ :class:`~.Path` objects:
350
+
351
+ * :meth:`~pathlib.Path.glob`
352
+ * :meth:`~pathlib.Path.iterdir`
353
+ * :meth:`~pathlib.Path.rglob`
354
+
355
+ .. versionchanged:: 4.14.0
356
+ Added the ``limiter`` keyword argument.
357
+ """
358
+
359
+ __slots__ = "_path", "_limiter", "__weakref__"
360
+
361
+ __weakref__: Any
362
+
363
+ def __init__(
364
+ self, *args: str | PathLike[str], limiter: CapacityLimiter | None = None
365
+ ) -> None:
366
+ if limiter is not None and not isinstance(limiter, CapacityLimiter):
367
+ raise TypeError(
368
+ f"limiter must be a CapacityLimiter or None, not "
369
+ f"{limiter.__class__.__name__}"
370
+ )
371
+
372
+ self._path: Final[pathlib.Path] = pathlib.Path(*args)
373
+ self._limiter = limiter
374
+
375
+ def __fspath__(self) -> str:
376
+ return self._path.__fspath__()
377
+
378
+ if sys.version_info >= (3, 15):
379
+
380
+ def __vfspath__(self) -> str:
381
+ return self._path.__vfspath__()
382
+
383
+ def __str__(self) -> str:
384
+ return self._path.__str__()
385
+
386
+ def __repr__(self) -> str:
387
+ return f"{self.__class__.__name__}({self.as_posix()!r})"
388
+
389
+ def __bytes__(self) -> bytes:
390
+ return self._path.__bytes__()
391
+
392
+ def __hash__(self) -> int:
393
+ return self._path.__hash__()
394
+
395
+ def __eq__(self, other: object) -> bool:
396
+ target = other._path if isinstance(other, Path) else other
397
+ return self._path.__eq__(target)
398
+
399
+ def __lt__(self, other: pathlib.PurePath | Path) -> bool:
400
+ target = other._path if isinstance(other, Path) else other
401
+ return self._path.__lt__(target)
402
+
403
+ def __le__(self, other: pathlib.PurePath | Path) -> bool:
404
+ target = other._path if isinstance(other, Path) else other
405
+ return self._path.__le__(target)
406
+
407
+ def __gt__(self, other: pathlib.PurePath | Path) -> bool:
408
+ target = other._path if isinstance(other, Path) else other
409
+ return self._path.__gt__(target)
410
+
411
+ def __ge__(self, other: pathlib.PurePath | Path) -> bool:
412
+ target = other._path if isinstance(other, Path) else other
413
+ return self._path.__ge__(target)
414
+
415
+ def __truediv__(self, other: str | PathLike[str]) -> Self:
416
+ return type(self)(self._path / other, limiter=self._limiter)
417
+
418
+ def __rtruediv__(self, other: str | PathLike[str]) -> Self:
419
+ return type(self)(other, limiter=self._limiter) / self
420
+
421
+ @property
422
+ def limiter(self) -> CapacityLimiter | None:
423
+ """The capacity limiter used by this path, if not the global limiter."""
424
+ return self._limiter
425
+
426
+ @property
427
+ def parts(self) -> tuple[str, ...]:
428
+ return self._path.parts
429
+
430
+ @property
431
+ def drive(self) -> str:
432
+ return self._path.drive
433
+
434
+ @property
435
+ def root(self) -> str:
436
+ return self._path.root
437
+
438
+ @property
439
+ def anchor(self) -> str:
440
+ return self._path.anchor
441
+
442
+ @property
443
+ def parents(self) -> Sequence[Self]:
444
+ return tuple(type(self)(p, limiter=self._limiter) for p in self._path.parents)
445
+
446
+ @property
447
+ def parent(self) -> Self:
448
+ return type(self)(self._path.parent, limiter=self._limiter)
449
+
450
+ @property
451
+ def name(self) -> str:
452
+ return self._path.name
453
+
454
+ @property
455
+ def suffix(self) -> str:
456
+ return self._path.suffix
457
+
458
+ @property
459
+ def suffixes(self) -> list[str]:
460
+ return self._path.suffixes
461
+
462
+ @property
463
+ def stem(self) -> str:
464
+ return self._path.stem
465
+
466
+ async def absolute(self) -> Self:
467
+ path = await to_thread.run_sync(self._path.absolute, limiter=self._limiter)
468
+ return type(self)(path, limiter=self._limiter)
469
+
470
+ def as_posix(self) -> str:
471
+ return self._path.as_posix()
472
+
473
+ def as_uri(self) -> str:
474
+ return self._path.as_uri()
475
+
476
+ if sys.version_info >= (3, 13):
477
+ parser: ClassVar[ModuleType] = pathlib.Path.parser
478
+
479
+ @classmethod
480
+ def from_uri(cls, uri: str, *, limiter: CapacityLimiter | None = None) -> Self:
481
+ return cls(pathlib.Path.from_uri(uri), limiter=limiter)
482
+
483
+ def full_match(
484
+ self, path_pattern: str, *, case_sensitive: bool | None = None
485
+ ) -> bool:
486
+ return self._path.full_match(path_pattern, case_sensitive=case_sensitive)
487
+
488
+ def match(
489
+ self, path_pattern: str, *, case_sensitive: bool | None = None
490
+ ) -> bool:
491
+ return self._path.match(path_pattern, case_sensitive=case_sensitive)
492
+ else:
493
+
494
+ def match(self, path_pattern: str) -> bool:
495
+ return self._path.match(path_pattern)
496
+
497
+ if sys.version_info >= (3, 14):
498
+
499
+ @property
500
+ def info(self) -> PathInfo:
501
+ return self._path.info
502
+
503
+ async def copy(
504
+ self,
505
+ target: str | os.PathLike[str],
506
+ *,
507
+ follow_symlinks: bool = True,
508
+ preserve_metadata: bool = False,
509
+ ) -> Self:
510
+ func = partial(
511
+ self._path.copy,
512
+ follow_symlinks=follow_symlinks,
513
+ preserve_metadata=preserve_metadata,
514
+ )
515
+ return type(self)(
516
+ await to_thread.run_sync(
517
+ func, pathlib.Path(target), limiter=self._limiter
518
+ ),
519
+ limiter=self._limiter,
520
+ )
521
+
522
+ async def copy_into(
523
+ self,
524
+ target_dir: str | os.PathLike[str],
525
+ *,
526
+ follow_symlinks: bool = True,
527
+ preserve_metadata: bool = False,
528
+ ) -> Self:
529
+ func = partial(
530
+ self._path.copy_into,
531
+ follow_symlinks=follow_symlinks,
532
+ preserve_metadata=preserve_metadata,
533
+ )
534
+ return type(self)(
535
+ await to_thread.run_sync(
536
+ func, pathlib.Path(target_dir), limiter=self._limiter
537
+ ),
538
+ limiter=self._limiter,
539
+ )
540
+
541
+ async def move(self, target: str | os.PathLike[str]) -> Self:
542
+ # Upstream does not handle anyio.Path properly as a PathLike
543
+ target = pathlib.Path(target)
544
+ return type(self)(
545
+ await to_thread.run_sync(
546
+ self._path.move, target, limiter=self._limiter
547
+ ),
548
+ limiter=self._limiter,
549
+ )
550
+
551
+ async def move_into(
552
+ self,
553
+ target_dir: str | os.PathLike[str],
554
+ ) -> Self:
555
+ return type(self)(
556
+ await to_thread.run_sync(
557
+ self._path.move_into, target_dir, limiter=self._limiter
558
+ ),
559
+ limiter=self._limiter,
560
+ )
561
+
562
+ def is_relative_to(self, other: str | PathLike[str]) -> bool:
563
+ try:
564
+ self.relative_to(other)
565
+ return True
566
+ except ValueError:
567
+ return False
568
+
569
+ async def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None:
570
+ func = partial(os.chmod, follow_symlinks=follow_symlinks)
571
+ return await to_thread.run_sync(func, self._path, mode, limiter=self._limiter)
572
+
573
+ @classmethod
574
+ async def cwd(cls, *, limiter: CapacityLimiter | None = None) -> Self:
575
+ path = await to_thread.run_sync(pathlib.Path.cwd, limiter=limiter)
576
+ return cls(path, limiter=limiter)
577
+
578
+ async def exists(self) -> bool:
579
+ return await to_thread.run_sync(
580
+ self._path.exists, abandon_on_cancel=True, limiter=self._limiter
581
+ )
582
+
583
+ async def expanduser(self) -> Self:
584
+ return type(self)(
585
+ await to_thread.run_sync(
586
+ self._path.expanduser, abandon_on_cancel=True, limiter=self._limiter
587
+ ),
588
+ limiter=self._limiter,
589
+ )
590
+
591
+ if sys.version_info < (3, 12):
592
+ # Python 3.11 and earlier
593
+ def glob(self, pattern: str) -> AsyncIterator[Self]:
594
+ gen = self._path.glob(pattern)
595
+ return _PathIterator(gen, self._limiter, type(self))
596
+ elif (3, 12) <= sys.version_info < (3, 13):
597
+ # changed in Python 3.12:
598
+ # - The case_sensitive parameter was added.
599
+ def glob(
600
+ self,
601
+ pattern: str,
602
+ *,
603
+ case_sensitive: bool | None = None,
604
+ ) -> AsyncIterator[Self]:
605
+ gen = self._path.glob(pattern, case_sensitive=case_sensitive)
606
+ return _PathIterator(gen, self._limiter, type(self))
607
+ elif sys.version_info >= (3, 13):
608
+ # Changed in Python 3.13:
609
+ # - The recurse_symlinks parameter was added.
610
+ # - The pattern parameter accepts a path-like object.
611
+ def glob( # type: ignore[misc] # mypy doesn't allow for differing signatures in a conditional block
612
+ self,
613
+ pattern: str | PathLike[str],
614
+ *,
615
+ case_sensitive: bool | None = None,
616
+ recurse_symlinks: bool = False,
617
+ ) -> AsyncIterator[Self]:
618
+ gen = self._path.glob(
619
+ pattern, # type: ignore[arg-type]
620
+ case_sensitive=case_sensitive,
621
+ recurse_symlinks=recurse_symlinks,
622
+ )
623
+ return _PathIterator(gen, self._limiter, type(self))
624
+
625
+ async def group(self) -> str:
626
+ return await to_thread.run_sync(
627
+ self._path.group, abandon_on_cancel=True, limiter=self._limiter
628
+ )
629
+
630
+ async def hardlink_to(
631
+ self, target: str | bytes | PathLike[str] | PathLike[bytes]
632
+ ) -> None:
633
+ if isinstance(target, Path):
634
+ target = target._path
635
+
636
+ await to_thread.run_sync(os.link, target, self, limiter=self._limiter)
637
+
638
+ @classmethod
639
+ async def home(cls, *, limiter: CapacityLimiter | None = None) -> Self:
640
+ home_path = await to_thread.run_sync(pathlib.Path.home, limiter=limiter)
641
+ return cls(home_path, limiter=limiter)
642
+
643
+ def is_absolute(self) -> bool:
644
+ return self._path.is_absolute()
645
+
646
+ async def is_block_device(self) -> bool:
647
+ return await to_thread.run_sync(
648
+ self._path.is_block_device, abandon_on_cancel=True, limiter=self._limiter
649
+ )
650
+
651
+ async def is_char_device(self) -> bool:
652
+ return await to_thread.run_sync(
653
+ self._path.is_char_device, abandon_on_cancel=True, limiter=self._limiter
654
+ )
655
+
656
+ async def is_dir(self) -> bool:
657
+ return await to_thread.run_sync(
658
+ self._path.is_dir, abandon_on_cancel=True, limiter=self._limiter
659
+ )
660
+
661
+ async def is_fifo(self) -> bool:
662
+ return await to_thread.run_sync(
663
+ self._path.is_fifo, abandon_on_cancel=True, limiter=self._limiter
664
+ )
665
+
666
+ async def is_file(self) -> bool:
667
+ return await to_thread.run_sync(
668
+ self._path.is_file, abandon_on_cancel=True, limiter=self._limiter
669
+ )
670
+
671
+ if sys.version_info >= (3, 12):
672
+
673
+ async def is_junction(self) -> bool:
674
+ return await to_thread.run_sync(
675
+ self._path.is_junction, limiter=self._limiter
676
+ )
677
+
678
+ async def is_mount(self) -> bool:
679
+ return await to_thread.run_sync(
680
+ os.path.ismount, self._path, abandon_on_cancel=True, limiter=self._limiter
681
+ )
682
+
683
+ if sys.version_info < (3, 15):
684
+
685
+ def is_reserved(self) -> bool:
686
+ return self._path.is_reserved()
687
+
688
+ async def is_socket(self) -> bool:
689
+ return await to_thread.run_sync(
690
+ self._path.is_socket, abandon_on_cancel=True, limiter=self._limiter
691
+ )
692
+
693
+ async def is_symlink(self) -> bool:
694
+ return await to_thread.run_sync(
695
+ self._path.is_symlink, abandon_on_cancel=True, limiter=self._limiter
696
+ )
697
+
698
+ async def iterdir(self) -> AsyncIterator[Self]:
699
+ gen = (
700
+ self._path.iterdir()
701
+ if sys.version_info < (3, 13)
702
+ else await to_thread.run_sync(
703
+ self._path.iterdir, abandon_on_cancel=True, limiter=self._limiter
704
+ )
705
+ )
706
+ async for path in _PathIterator(gen, self._limiter, type(self)):
707
+ yield path
708
+
709
+ def joinpath(self, *args: str | PathLike[str]) -> Self:
710
+ return type(self)(self._path.joinpath(*args), limiter=self._limiter)
711
+
712
+ async def lchmod(self, mode: int) -> None:
713
+ await to_thread.run_sync(self._path.lchmod, mode, limiter=self._limiter)
714
+
715
+ async def lstat(self) -> os.stat_result:
716
+ return await to_thread.run_sync(
717
+ self._path.lstat, abandon_on_cancel=True, limiter=self._limiter
718
+ )
719
+
720
+ async def mkdir(
721
+ self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False
722
+ ) -> None:
723
+ await to_thread.run_sync(
724
+ self._path.mkdir, mode, parents, exist_ok, limiter=self._limiter
725
+ )
726
+
727
+ @overload
728
+ async def open(
729
+ self,
730
+ mode: OpenBinaryMode,
731
+ buffering: int = ...,
732
+ encoding: str | None = ...,
733
+ errors: str | None = ...,
734
+ newline: str | None = ...,
735
+ ) -> AsyncFile[bytes]: ...
736
+
737
+ @overload
738
+ async def open(
739
+ self,
740
+ mode: OpenTextMode = ...,
741
+ buffering: int = ...,
742
+ encoding: str | None = ...,
743
+ errors: str | None = ...,
744
+ newline: str | None = ...,
745
+ ) -> AsyncFile[str]: ...
746
+
747
+ async def open(
748
+ self,
749
+ mode: str = "r",
750
+ buffering: int = -1,
751
+ encoding: str | None = None,
752
+ errors: str | None = None,
753
+ newline: str | None = None,
754
+ ) -> AsyncFile[Any]:
755
+ fp = await to_thread.run_sync(
756
+ self._path.open,
757
+ mode,
758
+ buffering,
759
+ encoding,
760
+ errors,
761
+ newline,
762
+ limiter=self._limiter,
763
+ )
764
+ return AsyncFile(fp, limiter=self._limiter)
765
+
766
+ async def owner(self) -> str:
767
+ return await to_thread.run_sync(
768
+ self._path.owner, abandon_on_cancel=True, limiter=self._limiter
769
+ )
770
+
771
+ async def read_bytes(self) -> bytes:
772
+ return await to_thread.run_sync(self._path.read_bytes, limiter=self._limiter)
773
+
774
+ async def read_text(
775
+ self, encoding: str | None = None, errors: str | None = None
776
+ ) -> str:
777
+ return await to_thread.run_sync(
778
+ self._path.read_text, encoding, errors, limiter=self._limiter
779
+ )
780
+
781
+ if sys.version_info >= (3, 12):
782
+
783
+ def relative_to(
784
+ self, *other: str | PathLike[str], walk_up: bool = False
785
+ ) -> Self:
786
+ # relative_to() should work with any PathLike but it doesn't
787
+ others = [pathlib.Path(other) for other in other]
788
+ return type(self)(
789
+ self._path.relative_to(*others, walk_up=walk_up), limiter=self._limiter
790
+ )
791
+
792
+ else:
793
+
794
+ def relative_to(self, *other: str | PathLike[str]) -> Self:
795
+ return type(self)(self._path.relative_to(*other), limiter=self._limiter)
796
+
797
+ async def readlink(self) -> Self:
798
+ target = await to_thread.run_sync(
799
+ os.readlink, self._path, limiter=self._limiter
800
+ )
801
+ return type(self)(target, limiter=self._limiter)
802
+
803
+ async def rename(self, target: str | pathlib.PurePath | Path) -> Self:
804
+ if isinstance(target, Path):
805
+ target = target._path
806
+
807
+ await to_thread.run_sync(self._path.rename, target, limiter=self._limiter)
808
+ return type(self)(target, limiter=self._limiter)
809
+
810
+ async def replace(self, target: str | pathlib.PurePath | Path) -> Self:
811
+ if isinstance(target, Path):
812
+ target = target._path
813
+
814
+ await to_thread.run_sync(self._path.replace, target, limiter=self._limiter)
815
+ return type(self)(target, limiter=self._limiter)
816
+
817
+ async def resolve(self, strict: bool = False) -> Self:
818
+ func = partial(self._path.resolve, strict=strict)
819
+ return type(self)(
820
+ await to_thread.run_sync(
821
+ func, abandon_on_cancel=True, limiter=self._limiter
822
+ ),
823
+ limiter=self._limiter,
824
+ )
825
+
826
+ if sys.version_info < (3, 12):
827
+ # Pre Python 3.12
828
+ def rglob(self, pattern: str) -> AsyncIterator[Self]:
829
+ gen = self._path.rglob(pattern)
830
+ return _PathIterator(gen, self._limiter, type(self))
831
+ elif (3, 12) <= sys.version_info < (3, 13):
832
+ # Changed in Python 3.12:
833
+ # - The case_sensitive parameter was added.
834
+ def rglob(
835
+ self, pattern: str, *, case_sensitive: bool | None = None
836
+ ) -> AsyncIterator[Self]:
837
+ gen = self._path.rglob(pattern, case_sensitive=case_sensitive)
838
+ return _PathIterator(gen, self._limiter, type(self))
839
+ elif sys.version_info >= (3, 13):
840
+ # Changed in Python 3.13:
841
+ # - The recurse_symlinks parameter was added.
842
+ # - The pattern parameter accepts a path-like object.
843
+ def rglob( # type: ignore[misc] # mypy doesn't allow for differing signatures in a conditional block
844
+ self,
845
+ pattern: str | PathLike[str],
846
+ *,
847
+ case_sensitive: bool | None = None,
848
+ recurse_symlinks: bool = False,
849
+ ) -> AsyncIterator[Self]:
850
+ gen = self._path.rglob(
851
+ pattern, # type: ignore[arg-type]
852
+ case_sensitive=case_sensitive,
853
+ recurse_symlinks=recurse_symlinks,
854
+ )
855
+ return _PathIterator(gen, self._limiter, type(self))
856
+
857
+ async def rmdir(self) -> None:
858
+ await to_thread.run_sync(self._path.rmdir, limiter=self._limiter)
859
+
860
+ async def samefile(self, other_path: str | PathLike[str]) -> bool:
861
+ if isinstance(other_path, Path):
862
+ other_path = other_path._path
863
+
864
+ return await to_thread.run_sync(
865
+ self._path.samefile,
866
+ other_path,
867
+ abandon_on_cancel=True,
868
+ limiter=self._limiter,
869
+ )
870
+
871
+ async def stat(self, *, follow_symlinks: bool = True) -> os.stat_result:
872
+ func = partial(os.stat, follow_symlinks=follow_symlinks)
873
+ return await to_thread.run_sync(
874
+ func, self._path, abandon_on_cancel=True, limiter=self._limiter
875
+ )
876
+
877
+ async def symlink_to(
878
+ self,
879
+ target: str | bytes | PathLike[str] | PathLike[bytes],
880
+ target_is_directory: bool = False,
881
+ ) -> None:
882
+ if isinstance(target, Path):
883
+ target = target._path
884
+
885
+ await to_thread.run_sync(
886
+ self._path.symlink_to, target, target_is_directory, limiter=self._limiter
887
+ )
888
+
889
+ async def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None:
890
+ await to_thread.run_sync(
891
+ self._path.touch, mode, exist_ok, limiter=self._limiter
892
+ )
893
+
894
+ async def unlink(self, missing_ok: bool = False) -> None:
895
+ try:
896
+ await to_thread.run_sync(self._path.unlink, limiter=self._limiter)
897
+ except FileNotFoundError:
898
+ if not missing_ok:
899
+ raise
900
+
901
+ if sys.version_info >= (3, 12):
902
+
903
+ async def walk(
904
+ self,
905
+ top_down: bool = True,
906
+ on_error: Callable[[OSError], object] | None = None,
907
+ follow_symlinks: bool = False,
908
+ ) -> AsyncIterator[tuple[Self, list[str], list[str]]]:
909
+ def get_next_value() -> tuple[pathlib.Path, list[str], list[str]] | None:
910
+ try:
911
+ return next(gen)
912
+ except StopIteration:
913
+ return None
914
+
915
+ gen = self._path.walk(top_down, on_error, follow_symlinks)
916
+ while True:
917
+ value = await to_thread.run_sync(get_next_value, limiter=self._limiter)
918
+ if value is None:
919
+ return
920
+
921
+ root, dirs, paths = value
922
+ yield type(self)(root, limiter=self._limiter), dirs, paths
923
+
924
+ def with_name(self, name: str) -> Self:
925
+ return type(self)(self._path.with_name(name), limiter=self._limiter)
926
+
927
+ def with_stem(self, stem: str) -> Self:
928
+ return type(self)(
929
+ self._path.with_name(stem + self._path.suffix), limiter=self._limiter
930
+ )
931
+
932
+ def with_suffix(self, suffix: str) -> Self:
933
+ return type(self)(self._path.with_suffix(suffix), limiter=self._limiter)
934
+
935
+ def with_segments(self, *pathsegments: str | PathLike[str]) -> Self:
936
+ return type(self)(*pathsegments, limiter=self._limiter)
937
+
938
+ async def write_bytes(self, data: ReadableBuffer) -> int:
939
+ return await to_thread.run_sync(
940
+ self._path.write_bytes, data, limiter=self._limiter
941
+ )
942
+
943
+ async def write_text(
944
+ self,
945
+ data: str,
946
+ encoding: str | None = None,
947
+ errors: str | None = None,
948
+ newline: str | None = None,
949
+ ) -> int:
950
+ return await to_thread.run_sync(
951
+ self._path.write_text,
952
+ data,
953
+ encoding,
954
+ errors,
955
+ newline,
956
+ limiter=self._limiter,
957
+ )
958
+
959
+
960
+ PathLike.register(Path)
.venv/lib/python3.13/site-packages/anyio/_core/_resources.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from ..abc import AsyncResource
4
+ from ._tasks import CancelScope
5
+
6
+
7
+ async def aclose_forcefully(resource: AsyncResource) -> None:
8
+ """
9
+ Close an asynchronous resource in a cancelled scope.
10
+
11
+ Doing this closes the resource without waiting on anything.
12
+
13
+ :param resource: the resource to close
14
+
15
+ """
16
+ with CancelScope() as scope:
17
+ scope.cancel()
18
+ await resource.aclose()
.venv/lib/python3.13/site-packages/anyio/_core/_signals.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import AsyncIterator
4
+ from contextlib import AbstractContextManager
5
+ from signal import Signals
6
+
7
+ from ._eventloop import get_async_backend
8
+
9
+
10
+ def open_signal_receiver(
11
+ *signals: Signals,
12
+ ) -> AbstractContextManager[AsyncIterator[Signals]]:
13
+ """
14
+ Start receiving operating system signals.
15
+
16
+ :param signals: signals to receive (e.g. ``signal.SIGINT``)
17
+ :return: an asynchronous context manager for an asynchronous iterator which yields
18
+ signal numbers
19
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
20
+ current thread
21
+
22
+ .. warning:: Windows does not support signals natively so it is best to avoid
23
+ relying on this in cross-platform applications.
24
+
25
+ .. warning:: On asyncio, this permanently replaces any previous signal handler for
26
+ the given signals, as set via :meth:`~asyncio.loop.add_signal_handler`.
27
+
28
+ """
29
+ return get_async_backend().open_signal_receiver(*signals)
.venv/lib/python3.13/site-packages/anyio/_core/_sockets.py ADDED
@@ -0,0 +1,1011 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import errno
4
+ import os
5
+ import socket
6
+ import ssl
7
+ import stat
8
+ import sys
9
+ from collections.abc import Awaitable
10
+ from dataclasses import dataclass
11
+ from ipaddress import IPv4Address, IPv6Address, ip_address
12
+ from os import PathLike, chmod
13
+ from socket import AddressFamily, SocketKind
14
+ from typing import TYPE_CHECKING, Any, Literal, cast, overload
15
+
16
+ from .. import ConnectionFailed, to_thread
17
+ from ..abc import (
18
+ ByteStreamConnectable,
19
+ ConnectedUDPSocket,
20
+ ConnectedUNIXDatagramSocket,
21
+ IPAddressType,
22
+ IPSockAddrType,
23
+ SocketListener,
24
+ SocketStream,
25
+ UDPSocket,
26
+ UNIXDatagramSocket,
27
+ UNIXSocketStream,
28
+ )
29
+ from ..streams.stapled import MultiListener
30
+ from ..streams.tls import TLSConnectable, TLSStream
31
+ from ._eventloop import get_async_backend
32
+ from ._resources import aclose_forcefully
33
+ from ._synchronization import Event
34
+ from ._tasks import create_task_group, move_on_after
35
+
36
+ if TYPE_CHECKING:
37
+ from _typeshed import FileDescriptorLike
38
+ else:
39
+ FileDescriptorLike = object
40
+
41
+ if sys.version_info < (3, 11):
42
+ from exceptiongroup import ExceptionGroup
43
+
44
+ if sys.version_info >= (3, 12):
45
+ from typing import override
46
+ else:
47
+ from typing_extensions import override
48
+
49
+ if sys.version_info < (3, 13):
50
+ from typing_extensions import deprecated
51
+ else:
52
+ from warnings import deprecated
53
+
54
+ IPPROTO_IPV6 = getattr(socket, "IPPROTO_IPV6", 41) # https://bugs.python.org/issue29515
55
+
56
+ AnyIPAddressFamily = Literal[
57
+ AddressFamily.AF_UNSPEC, AddressFamily.AF_INET, AddressFamily.AF_INET6
58
+ ]
59
+ IPAddressFamily = Literal[AddressFamily.AF_INET, AddressFamily.AF_INET6]
60
+
61
+
62
+ def idna2008_resolve(host: str) -> bytes:
63
+ try:
64
+ return host.encode("ascii")
65
+ except UnicodeEncodeError:
66
+ import idna
67
+
68
+ return idna.encode(host, uts46=True)
69
+
70
+
71
+ # tls_hostname given
72
+ @overload
73
+ async def connect_tcp(
74
+ remote_host: IPAddressType,
75
+ remote_port: int,
76
+ *,
77
+ local_host: IPAddressType | None = ...,
78
+ local_port: int | None = ...,
79
+ ssl_context: ssl.SSLContext | None = ...,
80
+ tls_standard_compatible: bool = ...,
81
+ tls_hostname: str,
82
+ happy_eyeballs_delay: float = ...,
83
+ ) -> TLSStream: ...
84
+
85
+
86
+ # ssl_context given
87
+ @overload
88
+ async def connect_tcp(
89
+ remote_host: IPAddressType,
90
+ remote_port: int,
91
+ *,
92
+ local_host: IPAddressType | None = ...,
93
+ local_port: int | None = ...,
94
+ ssl_context: ssl.SSLContext,
95
+ tls_standard_compatible: bool = ...,
96
+ tls_hostname: str | None = ...,
97
+ happy_eyeballs_delay: float = ...,
98
+ ) -> TLSStream: ...
99
+
100
+
101
+ # tls=True
102
+ @overload
103
+ async def connect_tcp(
104
+ remote_host: IPAddressType,
105
+ remote_port: int,
106
+ *,
107
+ local_host: IPAddressType | None = ...,
108
+ local_port: int | None = ...,
109
+ tls: Literal[True],
110
+ ssl_context: ssl.SSLContext | None = ...,
111
+ tls_standard_compatible: bool = ...,
112
+ tls_hostname: str | None = ...,
113
+ happy_eyeballs_delay: float = ...,
114
+ ) -> TLSStream: ...
115
+
116
+
117
+ # tls=False
118
+ @overload
119
+ async def connect_tcp(
120
+ remote_host: IPAddressType,
121
+ remote_port: int,
122
+ *,
123
+ local_host: IPAddressType | None = ...,
124
+ local_port: int | None = ...,
125
+ tls: Literal[False],
126
+ ssl_context: ssl.SSLContext | None = ...,
127
+ tls_standard_compatible: bool = ...,
128
+ tls_hostname: str | None = ...,
129
+ happy_eyeballs_delay: float = ...,
130
+ ) -> SocketStream: ...
131
+
132
+
133
+ # No TLS arguments
134
+ @overload
135
+ async def connect_tcp(
136
+ remote_host: IPAddressType,
137
+ remote_port: int,
138
+ *,
139
+ local_host: IPAddressType | None = ...,
140
+ local_port: int | None = ...,
141
+ happy_eyeballs_delay: float = ...,
142
+ ) -> SocketStream: ...
143
+
144
+
145
+ async def connect_tcp(
146
+ remote_host: IPAddressType,
147
+ remote_port: int,
148
+ *,
149
+ local_host: IPAddressType | None = None,
150
+ local_port: int | None = None,
151
+ tls: bool = False,
152
+ ssl_context: ssl.SSLContext | None = None,
153
+ tls_standard_compatible: bool = True,
154
+ tls_hostname: str | None = None,
155
+ happy_eyeballs_delay: float = 0.25,
156
+ ) -> SocketStream | TLSStream:
157
+ """
158
+ Connect to a host using the TCP protocol.
159
+
160
+ This function implements the stateless version of the Happy Eyeballs algorithm (RFC
161
+ 6555). If ``remote_host`` is a host name that resolves to multiple IP addresses,
162
+ each one is tried until one connection attempt succeeds. If the first attempt does
163
+ not connected within 250 milliseconds, a second attempt is started using the next
164
+ address in the list, and so on. On IPv6 enabled systems, an IPv6 address (if
165
+ available) is tried first.
166
+
167
+ When the connection has been established, a TLS handshake will be done if either
168
+ ``ssl_context`` or ``tls_hostname`` is not ``None``, or if ``tls`` is ``True``.
169
+
170
+ :param remote_host: the IP address or host name to connect to
171
+ :param remote_port: port on the target host to connect to
172
+ :param local_host: the interface address or name to bind the socket to before
173
+ connecting
174
+ :param local_port: the local port to bind to (requires ``local_host`` to also be
175
+ set)
176
+ :param tls: ``True`` to do a TLS handshake with the connected stream and return a
177
+ :class:`~anyio.streams.tls.TLSStream` instead
178
+ :param ssl_context: the SSL context object to use (if omitted, a default context is
179
+ created)
180
+ :param tls_standard_compatible: If ``True``, performs the TLS shutdown handshake
181
+ before closing the stream and requires that the server does this as well.
182
+ Otherwise, :exc:`~ssl.SSLEOFError` may be raised during reads from the stream.
183
+ Some protocols, such as HTTP, require this option to be ``False``.
184
+ See :meth:`~ssl.SSLContext.wrap_socket` for details.
185
+ :param tls_hostname: host name to check the server certificate against (defaults to
186
+ the value of ``remote_host``)
187
+ :param happy_eyeballs_delay: delay (in seconds) before starting the next connection
188
+ attempt
189
+ :return: a socket stream object if no TLS handshake was done, otherwise a TLS stream
190
+ :raises ConnectionFailed: if the connection fails
191
+
192
+ """
193
+ # Placed here due to https://github.com/python/mypy/issues/7057
194
+ connected_stream: SocketStream | None = None
195
+
196
+ async def try_connect(remote_host: str, event: Event) -> None:
197
+ nonlocal connected_stream
198
+ try:
199
+ stream = await asynclib.connect_tcp(remote_host, remote_port, local_address)
200
+ except OSError as exc:
201
+ oserrors.append(exc)
202
+ return
203
+ else:
204
+ if connected_stream is None:
205
+ connected_stream = stream
206
+ tg.cancel_scope.cancel()
207
+ else:
208
+ await stream.aclose()
209
+ finally:
210
+ event.set()
211
+
212
+ asynclib = get_async_backend()
213
+ local_address: IPSockAddrType | None = None
214
+ family = socket.AF_UNSPEC
215
+ if local_host:
216
+ gai_res = await getaddrinfo(str(local_host), local_port)
217
+ family, *_, local_address = gai_res[0]
218
+
219
+ target_host = str(remote_host)
220
+ try:
221
+ addr_obj = ip_address(remote_host)
222
+ except ValueError:
223
+ addr_obj = None
224
+
225
+ if addr_obj is not None:
226
+ if isinstance(addr_obj, IPv6Address):
227
+ target_addrs = [(socket.AF_INET6, addr_obj.compressed)]
228
+ else:
229
+ target_addrs = [(socket.AF_INET, addr_obj.compressed)]
230
+ else:
231
+ # getaddrinfo() will raise an exception if name resolution fails
232
+ gai_res = await getaddrinfo(
233
+ target_host, remote_port, family=family, type=socket.SOCK_STREAM
234
+ )
235
+
236
+ # Organize the list so that the first address is an IPv6 address (if available)
237
+ # and the second one is an IPv4 addresses. The rest can be in whatever order.
238
+ v6_found = v4_found = False
239
+ target_addrs = []
240
+ for af, *_, sa in gai_res:
241
+ if af == socket.AF_INET6 and not v6_found:
242
+ v6_found = True
243
+ target_addrs.insert(0, (af, sa[0]))
244
+ elif af == socket.AF_INET and not v4_found and v6_found:
245
+ v4_found = True
246
+ target_addrs.insert(1, (af, sa[0]))
247
+ else:
248
+ target_addrs.append((af, sa[0]))
249
+
250
+ oserrors: list[OSError] = []
251
+ try:
252
+ async with create_task_group() as tg:
253
+ for _af, addr in target_addrs:
254
+ event = Event()
255
+ tg.start_soon(try_connect, addr, event)
256
+ with move_on_after(happy_eyeballs_delay):
257
+ await event.wait()
258
+
259
+ if connected_stream is None:
260
+ cause = (
261
+ oserrors[0]
262
+ if len(oserrors) == 1
263
+ else ExceptionGroup("multiple connection attempts failed", oserrors)
264
+ )
265
+ raise OSError("All connection attempts failed") from cause
266
+ finally:
267
+ oserrors.clear()
268
+
269
+ if tls or tls_hostname or ssl_context:
270
+ try:
271
+ return await TLSStream.wrap(
272
+ connected_stream,
273
+ server_side=False,
274
+ hostname=tls_hostname or str(remote_host),
275
+ ssl_context=ssl_context,
276
+ standard_compatible=tls_standard_compatible,
277
+ )
278
+ except BaseException:
279
+ await aclose_forcefully(connected_stream)
280
+ raise
281
+
282
+ return connected_stream
283
+
284
+
285
+ async def connect_unix(path: str | bytes | PathLike[Any]) -> UNIXSocketStream:
286
+ """
287
+ Connect to the given UNIX socket.
288
+
289
+ Not available on Windows.
290
+
291
+ :param path: path to the socket
292
+ :return: a socket stream object
293
+ :raises ConnectionFailed: if the connection fails
294
+
295
+ """
296
+ path = os.fspath(path)
297
+ return await get_async_backend().connect_unix(path)
298
+
299
+
300
+ async def create_tcp_listener(
301
+ *,
302
+ local_host: IPAddressType | None = None,
303
+ local_port: int = 0,
304
+ family: AnyIPAddressFamily = socket.AddressFamily.AF_UNSPEC,
305
+ backlog: int = 65536,
306
+ reuse_port: bool = False,
307
+ ) -> MultiListener[SocketStream]:
308
+ """
309
+ Create a TCP socket listener.
310
+
311
+ :param local_port: port number to listen on
312
+ :param local_host: IP address of the interface to listen on. If omitted, listen on
313
+ all IPv4 and IPv6 interfaces. To listen on all interfaces on a specific address
314
+ family, use ``0.0.0.0`` for IPv4 or ``::`` for IPv6.
315
+ :param family: address family (used if ``local_host`` was omitted)
316
+ :param backlog: maximum number of queued incoming connections (up to a maximum of
317
+ 2**16, or 65536)
318
+ :param reuse_port: ``True`` to allow multiple sockets to bind to the same
319
+ address/port (not supported on Windows)
320
+ :return: a multi-listener object containing one or more socket listeners
321
+ :raises OSError: if there's an error creating a socket, or binding to one or more
322
+ interfaces failed
323
+
324
+ """
325
+ asynclib = get_async_backend()
326
+ backlog = min(backlog, 65536)
327
+ local_host = str(local_host) if local_host is not None else None
328
+
329
+ def setup_raw_socket(
330
+ fam: AddressFamily,
331
+ bind_addr: tuple[str, int] | tuple[str, int, int, int],
332
+ *,
333
+ v6only: bool = True,
334
+ ) -> socket.socket:
335
+ sock = socket.socket(fam)
336
+ try:
337
+ sock.setblocking(False)
338
+
339
+ if fam == AddressFamily.AF_INET6:
340
+ sock.setsockopt(IPPROTO_IPV6, socket.IPV6_V6ONLY, v6only)
341
+
342
+ # For Windows, enable exclusive address use. For others, enable address
343
+ # reuse.
344
+ if sys.platform == "win32":
345
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
346
+ else:
347
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
348
+
349
+ if reuse_port:
350
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
351
+
352
+ # Workaround for #554
353
+ if fam == socket.AF_INET6 and "%" in bind_addr[0]:
354
+ addr, scope_id = bind_addr[0].split("%", 1)
355
+ bind_addr = (addr, bind_addr[1], 0, int(scope_id))
356
+
357
+ sock.bind(bind_addr)
358
+ sock.listen(backlog)
359
+ except BaseException:
360
+ sock.close()
361
+ raise
362
+
363
+ return sock
364
+
365
+ # We passing type=0 on non-Windows platforms as a workaround for a uvloop bug
366
+ # where we don't get the correct scope ID for IPv6 link-local addresses when passing
367
+ # type=socket.SOCK_STREAM to getaddrinfo():
368
+ # https://github.com/MagicStack/uvloop/issues/539
369
+ gai_res = await getaddrinfo(
370
+ local_host,
371
+ local_port,
372
+ family=family,
373
+ type=socket.SOCK_STREAM if sys.platform == "win32" else 0,
374
+ flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG,
375
+ )
376
+
377
+ # The set comprehension is here to work around a glibc bug:
378
+ # https://sourceware.org/bugzilla/show_bug.cgi?id=14969
379
+ sockaddrs = sorted({res for res in gai_res if res[1] == SocketKind.SOCK_STREAM})
380
+
381
+ # Special case for dual-stack binding on the "any" interface
382
+ if (
383
+ local_host is None
384
+ and family == AddressFamily.AF_UNSPEC
385
+ and socket.has_dualstack_ipv6()
386
+ and any(fam == AddressFamily.AF_INET6 for fam, *_ in gai_res)
387
+ ):
388
+ raw_socket = setup_raw_socket(
389
+ AddressFamily.AF_INET6, ("::", local_port), v6only=False
390
+ )
391
+ listener = asynclib.create_tcp_listener(raw_socket)
392
+ return MultiListener([listener])
393
+
394
+ errors: list[OSError] = []
395
+ try:
396
+ for _ in range(len(sockaddrs)):
397
+ listeners: list[SocketListener] = []
398
+ bound_ephemeral_port = local_port
399
+ try:
400
+ for fam, *_, sockaddr in sockaddrs:
401
+ sockaddr = sockaddr[0], bound_ephemeral_port, *sockaddr[2:]
402
+ raw_socket = setup_raw_socket(fam, sockaddr)
403
+
404
+ # Store the assigned port if an ephemeral port was requested, so
405
+ # we'll bind to the same port on all interfaces
406
+ if local_port == 0 and len(gai_res) > 1:
407
+ bound_ephemeral_port = raw_socket.getsockname()[1]
408
+
409
+ listeners.append(asynclib.create_tcp_listener(raw_socket))
410
+ except BaseException as exc:
411
+ for listener in listeners:
412
+ await listener.aclose()
413
+
414
+ # If an ephemeral port was requested but binding the assigned port
415
+ # failed for another interface, rotate the address list and try again
416
+ if (
417
+ isinstance(exc, OSError)
418
+ and exc.errno == errno.EADDRINUSE
419
+ and local_port == 0
420
+ and bound_ephemeral_port
421
+ ):
422
+ errors.append(exc)
423
+ sockaddrs.append(sockaddrs.pop(0))
424
+ continue
425
+
426
+ raise
427
+
428
+ return MultiListener(listeners)
429
+
430
+ raise OSError(
431
+ f"Could not create {len(sockaddrs)} listeners with a consistent port"
432
+ ) from ExceptionGroup("Several bind attempts failed", errors)
433
+ finally:
434
+ del errors # Prevent reference cycles
435
+
436
+
437
+ async def create_unix_listener(
438
+ path: str | bytes | PathLike[Any],
439
+ *,
440
+ mode: int | None = None,
441
+ backlog: int = 65536,
442
+ ) -> SocketListener:
443
+ """
444
+ Create a UNIX socket listener.
445
+
446
+ Not available on Windows.
447
+
448
+ :param path: path of the socket
449
+ :param mode: permissions to set on the socket
450
+ :param backlog: maximum number of queued incoming connections (up to a maximum of
451
+ 2**16, or 65536)
452
+ :return: a listener object
453
+
454
+ .. versionchanged:: 3.0
455
+ If a socket already exists on the file system in the given path, it will be
456
+ removed first.
457
+
458
+ """
459
+ backlog = min(backlog, 65536)
460
+ raw_socket = await setup_unix_local_socket(path, mode, socket.SOCK_STREAM)
461
+ try:
462
+ raw_socket.listen(backlog)
463
+ return get_async_backend().create_unix_listener(raw_socket)
464
+ except BaseException:
465
+ raw_socket.close()
466
+ raise
467
+
468
+
469
+ async def create_udp_socket(
470
+ family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC,
471
+ *,
472
+ local_host: IPAddressType | None = None,
473
+ local_port: int = 0,
474
+ reuse_port: bool = False,
475
+ ) -> UDPSocket:
476
+ """
477
+ Create a UDP socket.
478
+
479
+ If ``port`` has been given, the socket will be bound to this port on the local
480
+ machine, making this socket suitable for providing UDP based services.
481
+
482
+ :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically
483
+ determined from ``local_host`` if omitted
484
+ :param local_host: IP address or host name of the local interface to bind to
485
+ :param local_port: local port to bind to
486
+ :param reuse_port: ``True`` to allow multiple sockets to bind to the same
487
+ address/port (not supported on Windows)
488
+ :return: a UDP socket
489
+
490
+ """
491
+ if family is AddressFamily.AF_UNSPEC and not local_host:
492
+ raise ValueError('Either "family" or "local_host" must be given')
493
+
494
+ if local_host:
495
+ gai_res = await getaddrinfo(
496
+ str(local_host),
497
+ local_port,
498
+ family=family,
499
+ type=socket.SOCK_DGRAM,
500
+ flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG,
501
+ )
502
+ family = cast(AnyIPAddressFamily, gai_res[0][0])
503
+ local_address = gai_res[0][-1]
504
+ elif family is AddressFamily.AF_INET6:
505
+ local_address = ("::", 0)
506
+ else:
507
+ local_address = ("0.0.0.0", 0)
508
+
509
+ sock = await get_async_backend().create_udp_socket(
510
+ family, local_address, None, reuse_port
511
+ )
512
+ return cast(UDPSocket, sock)
513
+
514
+
515
+ async def create_connected_udp_socket(
516
+ remote_host: IPAddressType,
517
+ remote_port: int,
518
+ *,
519
+ family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC,
520
+ local_host: IPAddressType | None = None,
521
+ local_port: int = 0,
522
+ reuse_port: bool = False,
523
+ ) -> ConnectedUDPSocket:
524
+ """
525
+ Create a connected UDP socket.
526
+
527
+ Connected UDP sockets can only communicate with the specified remote host/port, an
528
+ any packets sent from other sources are dropped.
529
+
530
+ :param remote_host: remote host to set as the default target
531
+ :param remote_port: port on the remote host to set as the default target
532
+ :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically
533
+ determined from ``local_host`` or ``remote_host`` if omitted
534
+ :param local_host: IP address or host name of the local interface to bind to
535
+ :param local_port: local port to bind to
536
+ :param reuse_port: ``True`` to allow multiple sockets to bind to the same
537
+ address/port (not supported on Windows)
538
+ :return: a connected UDP socket
539
+
540
+ """
541
+ local_address = None
542
+ if local_host:
543
+ gai_res = await getaddrinfo(
544
+ str(local_host),
545
+ local_port,
546
+ family=family,
547
+ type=socket.SOCK_DGRAM,
548
+ flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG,
549
+ )
550
+ family = cast(AnyIPAddressFamily, gai_res[0][0])
551
+ local_address = gai_res[0][-1]
552
+
553
+ gai_res = await getaddrinfo(
554
+ str(remote_host), remote_port, family=family, type=socket.SOCK_DGRAM
555
+ )
556
+ family = cast(AnyIPAddressFamily, gai_res[0][0])
557
+ remote_address = gai_res[0][-1]
558
+
559
+ sock = await get_async_backend().create_udp_socket(
560
+ family, local_address, remote_address, reuse_port
561
+ )
562
+ return cast(ConnectedUDPSocket, sock)
563
+
564
+
565
+ async def create_unix_datagram_socket(
566
+ *,
567
+ local_path: None | str | bytes | PathLike[Any] = None,
568
+ local_mode: int | None = None,
569
+ ) -> UNIXDatagramSocket:
570
+ """
571
+ Create a UNIX datagram socket.
572
+
573
+ Not available on Windows.
574
+
575
+ If ``local_path`` has been given, the socket will be bound to this path, making this
576
+ socket suitable for receiving datagrams from other processes. Other processes can
577
+ send datagrams to this socket only if ``local_path`` is set.
578
+
579
+ If a socket already exists on the file system in the ``local_path``, it will be
580
+ removed first.
581
+
582
+ :param local_path: the path on which to bind to
583
+ :param local_mode: permissions to set on the local socket
584
+ :return: a UNIX datagram socket
585
+
586
+ """
587
+ raw_socket = await setup_unix_local_socket(
588
+ local_path, local_mode, socket.SOCK_DGRAM
589
+ )
590
+ return await get_async_backend().create_unix_datagram_socket(raw_socket, None)
591
+
592
+
593
+ async def create_connected_unix_datagram_socket(
594
+ remote_path: str | bytes | PathLike[Any],
595
+ *,
596
+ local_path: None | str | bytes | PathLike[Any] = None,
597
+ local_mode: int | None = None,
598
+ ) -> ConnectedUNIXDatagramSocket:
599
+ """
600
+ Create a connected UNIX datagram socket.
601
+
602
+ Connected datagram sockets can only communicate with the specified remote path.
603
+
604
+ If ``local_path`` has been given, the socket will be bound to this path, making
605
+ this socket suitable for receiving datagrams from other processes. Other processes
606
+ can send datagrams to this socket only if ``local_path`` is set.
607
+
608
+ If a socket already exists on the file system in the ``local_path``, it will be
609
+ removed first.
610
+
611
+ :param remote_path: the path to set as the default target
612
+ :param local_path: the path on which to bind to
613
+ :param local_mode: permissions to set on the local socket
614
+ :return: a connected UNIX datagram socket
615
+
616
+ """
617
+ remote_path = os.fspath(remote_path)
618
+ raw_socket = await setup_unix_local_socket(
619
+ local_path, local_mode, socket.SOCK_DGRAM
620
+ )
621
+ return await get_async_backend().create_unix_datagram_socket(
622
+ raw_socket, remote_path
623
+ )
624
+
625
+
626
+ async def getaddrinfo(
627
+ host: bytes | str | None,
628
+ port: str | int | None,
629
+ *,
630
+ family: int | AddressFamily = 0,
631
+ type: int | SocketKind = 0,
632
+ proto: int = 0,
633
+ flags: int = 0,
634
+ ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int]]]:
635
+ """
636
+ Look up a numeric IP address given a host name.
637
+
638
+ Internationalized domain names are translated according to the (non-transitional)
639
+ IDNA 2008 standard.
640
+
641
+ .. note:: 4-tuple IPv6 socket addresses are automatically converted to 2-tuples of
642
+ (host, port), unlike what :func:`socket.getaddrinfo` does.
643
+
644
+ :param host: host name
645
+ :param port: port number
646
+ :param family: socket family (`'AF_INET``, ...)
647
+ :param type: socket type (``SOCK_STREAM``, ...)
648
+ :param proto: protocol number
649
+ :param flags: flags to pass to upstream ``getaddrinfo()``
650
+ :return: list of tuples containing (family, type, proto, canonname, sockaddr)
651
+
652
+ .. seealso:: :func:`socket.getaddrinfo`
653
+
654
+ """
655
+ # Handle unicode hostnames
656
+ encoded_host = idna2008_resolve(host) if isinstance(host, str) else host
657
+ gai_res = await get_async_backend().getaddrinfo(
658
+ encoded_host, port, family=family, type=type, proto=proto, flags=flags
659
+ )
660
+ return [
661
+ (family, type, proto, canonname, convert_ipv6_sockaddr(sockaddr))
662
+ for family, type, proto, canonname, sockaddr in gai_res
663
+ # filter out IPv6 results when IPv6 is disabled
664
+ if not isinstance(sockaddr[0], int)
665
+ ]
666
+
667
+
668
+ def getnameinfo(sockaddr: IPSockAddrType, flags: int = 0) -> Awaitable[tuple[str, str]]:
669
+ """
670
+ Look up the host name of an IP address.
671
+
672
+ :param sockaddr: socket address (e.g. (ipaddress, port) for IPv4)
673
+ :param flags: flags to pass to upstream ``getnameinfo()``
674
+ :return: a tuple of (host name, service name)
675
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
676
+ current thread
677
+
678
+ .. seealso:: :func:`socket.getnameinfo`
679
+
680
+ """
681
+ return get_async_backend().getnameinfo(sockaddr, flags)
682
+
683
+
684
+ @deprecated("This function is deprecated; use `wait_readable` instead")
685
+ def wait_socket_readable(sock: socket.socket) -> Awaitable[None]:
686
+ """
687
+ .. deprecated:: 4.7.0
688
+ Use :func:`wait_readable` instead.
689
+
690
+ Wait until the given socket has data to be read.
691
+
692
+ .. warning:: Only use this on raw sockets that have not been wrapped by any higher
693
+ level constructs like socket streams!
694
+
695
+ :param sock: a socket object
696
+ :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the
697
+ socket to become readable
698
+ :raises ~anyio.BusyResourceError: if another task is already waiting for the socket
699
+ to become readable
700
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
701
+ current thread
702
+
703
+ """
704
+ return get_async_backend().wait_readable(sock.fileno())
705
+
706
+
707
+ @deprecated("This function is deprecated; use `wait_writable` instead")
708
+ def wait_socket_writable(sock: socket.socket) -> Awaitable[None]:
709
+ """
710
+ .. deprecated:: 4.7.0
711
+ Use :func:`wait_writable` instead.
712
+
713
+ Wait until the given socket can be written to.
714
+
715
+ This does **NOT** work on Windows when using the asyncio backend with a proactor
716
+ event loop (default on py3.8+).
717
+
718
+ .. warning:: Only use this on raw sockets that have not been wrapped by any higher
719
+ level constructs like socket streams!
720
+
721
+ :param sock: a socket object
722
+ :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the
723
+ socket to become writable
724
+ :raises ~anyio.BusyResourceError: if another task is already waiting for the socket
725
+ to become writable
726
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
727
+ current thread
728
+
729
+ """
730
+ return get_async_backend().wait_writable(sock.fileno())
731
+
732
+
733
+ def wait_readable(obj: FileDescriptorLike) -> Awaitable[None]:
734
+ """
735
+ Wait until the given object has data to be read.
736
+
737
+ On Unix systems, ``obj`` must either be an integer file descriptor, or else an
738
+ object with a ``.fileno()`` method which returns an integer file descriptor. Any
739
+ kind of file descriptor can be passed, though the exact semantics will depend on
740
+ your kernel. For example, this probably won't do anything useful for on-disk files.
741
+
742
+ On Windows systems, ``obj`` must either be an integer ``SOCKET`` handle, or else an
743
+ object with a ``.fileno()`` method which returns an integer ``SOCKET`` handle. File
744
+ descriptors aren't supported, and neither are handles that refer to anything besides
745
+ a ``SOCKET``.
746
+
747
+ On backends where this functionality is not natively provided (asyncio
748
+ ``ProactorEventLoop`` on Windows), it is provided using a separate selector thread
749
+ which is set to shut down when the interpreter shuts down.
750
+
751
+ .. warning:: Don't use this on raw sockets that have been wrapped by any higher
752
+ level constructs like socket streams!
753
+
754
+ :param obj: an object with a ``.fileno()`` method or an integer handle
755
+ :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the
756
+ object to become readable
757
+ :raises ~anyio.BusyResourceError: if another task is already waiting for the object
758
+ to become readable
759
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
760
+ current thread
761
+
762
+ """
763
+ return get_async_backend().wait_readable(obj)
764
+
765
+
766
+ def wait_writable(obj: FileDescriptorLike) -> Awaitable[None]:
767
+ """
768
+ Wait until the given object can be written to.
769
+
770
+ :param obj: an object with a ``.fileno()`` method or an integer handle
771
+ :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the
772
+ object to become writable
773
+ :raises ~anyio.BusyResourceError: if another task is already waiting for the object
774
+ to become writable
775
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
776
+ current thread
777
+
778
+ .. seealso:: See the documentation of :func:`wait_readable` for the definition of
779
+ ``obj`` and notes on backend compatibility.
780
+
781
+ .. warning:: Don't use this on raw sockets that have been wrapped by any higher
782
+ level constructs like socket streams!
783
+
784
+ """
785
+ return get_async_backend().wait_writable(obj)
786
+
787
+
788
+ def notify_closing(obj: FileDescriptorLike) -> None:
789
+ """
790
+ Call this before closing a file descriptor (on Unix) or socket (on
791
+ Windows). This will cause any `wait_readable` or `wait_writable`
792
+ calls on the given object to immediately wake up and raise
793
+ `~anyio.ClosedResourceError`.
794
+
795
+ This doesn't actually close the object – you still have to do that
796
+ yourself afterwards. Also, you want to be careful to make sure no
797
+ new tasks start waiting on the object in between when you call this
798
+ and when it's actually closed. So to close something properly, you
799
+ usually want to do these steps in order:
800
+
801
+ 1. Explicitly mark the object as closed, so that any new attempts
802
+ to use it will abort before they start.
803
+ 2. Call `notify_closing` to wake up any already-existing users.
804
+ 3. Actually close the object.
805
+
806
+ It's also possible to do them in a different order if that's more
807
+ convenient, *but only if* you make sure not to have any checkpoints in
808
+ between the steps. This way they all happen in a single atomic
809
+ step, so other tasks won't be able to tell what order they happened
810
+ in anyway.
811
+
812
+ :param obj: an object with a ``.fileno()`` method or an integer handle
813
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
814
+ current thread
815
+
816
+ """
817
+ get_async_backend().notify_closing(obj)
818
+
819
+
820
+ #
821
+ # Private API
822
+ #
823
+
824
+
825
+ def convert_ipv6_sockaddr(
826
+ sockaddr: tuple[str, int, int, int] | tuple[str, int],
827
+ ) -> tuple[str, int]:
828
+ """
829
+ Convert a 4-tuple IPv6 socket address to a 2-tuple (address, port) format.
830
+
831
+ If the scope ID is nonzero, it is added to the address, separated with ``%``.
832
+ Otherwise the flow id and scope id are simply cut off from the tuple.
833
+ Any other kinds of socket addresses are returned as-is.
834
+
835
+ :param sockaddr: the result of :meth:`~socket.socket.getsockname`
836
+ :return: the converted socket address
837
+
838
+ """
839
+ # This is more complicated than it should be because of MyPy
840
+ if isinstance(sockaddr, tuple) and len(sockaddr) == 4:
841
+ host, port, flowinfo, scope_id = sockaddr
842
+ if scope_id:
843
+ # PyPy (as of v7.3.11) leaves the interface name in the result, so
844
+ # we discard it and only get the scope ID from the end
845
+ # (https://foss.heptapod.net/pypy/pypy/-/issues/3938)
846
+ host = host.split("%")[0]
847
+
848
+ # Add scope_id to the address
849
+ return f"{host}%{scope_id}", port
850
+ else:
851
+ return host, port
852
+ else:
853
+ return sockaddr
854
+
855
+
856
+ async def setup_unix_local_socket(
857
+ path: None | str | bytes | PathLike[Any],
858
+ mode: int | None,
859
+ socktype: int,
860
+ ) -> socket.socket:
861
+ """
862
+ Create a UNIX local socket object, deleting the socket at the given path if it
863
+ exists.
864
+
865
+ Not available on Windows.
866
+
867
+ :param path: path of the socket
868
+ :param mode: permissions to set on the socket
869
+ :param socktype: socket.SOCK_STREAM or socket.SOCK_DGRAM
870
+
871
+ """
872
+ path_str: str | None
873
+ if path is not None:
874
+ path_str = os.fsdecode(path)
875
+
876
+ # Linux abstract namespace sockets aren't backed by a concrete file so skip stat call
877
+ if not path_str.startswith("\0"):
878
+ # Copied from pathlib...
879
+ try:
880
+ stat_result = os.stat(path)
881
+ except OSError as e:
882
+ if e.errno not in (
883
+ errno.ENOENT,
884
+ errno.ENOTDIR,
885
+ errno.EBADF,
886
+ errno.ELOOP,
887
+ ):
888
+ raise
889
+ else:
890
+ if stat.S_ISSOCK(stat_result.st_mode):
891
+ os.unlink(path)
892
+ else:
893
+ path_str = None
894
+
895
+ raw_socket = socket.socket(socket.AF_UNIX, socktype)
896
+ raw_socket.setblocking(False)
897
+
898
+ if path_str is not None:
899
+ try:
900
+ await to_thread.run_sync(raw_socket.bind, path_str, abandon_on_cancel=True)
901
+ if mode is not None:
902
+ await to_thread.run_sync(chmod, path_str, mode, abandon_on_cancel=True)
903
+ except BaseException:
904
+ raw_socket.close()
905
+ raise
906
+
907
+ return raw_socket
908
+
909
+
910
+ @dataclass
911
+ class TCPConnectable(ByteStreamConnectable):
912
+ """
913
+ Connects to a TCP server at the given host and port.
914
+
915
+ :param host: host name or IP address of the server
916
+ :param port: TCP port number of the server
917
+ """
918
+
919
+ host: str | IPv4Address | IPv6Address
920
+ port: int
921
+
922
+ def __post_init__(self) -> None:
923
+ if self.port < 1 or self.port > 65535:
924
+ raise ValueError("TCP port number out of range")
925
+
926
+ @override
927
+ async def connect(self) -> SocketStream:
928
+ try:
929
+ return await connect_tcp(self.host, self.port)
930
+ except OSError as exc:
931
+ raise ConnectionFailed(
932
+ f"error connecting to {self.host}:{self.port}: {exc}"
933
+ ) from exc
934
+
935
+
936
+ @dataclass
937
+ class UNIXConnectable(ByteStreamConnectable):
938
+ """
939
+ Connects to a UNIX domain socket at the given path.
940
+
941
+ :param path: the file system path of the socket
942
+ """
943
+
944
+ path: str | bytes | PathLike[str] | PathLike[bytes]
945
+
946
+ @override
947
+ async def connect(self) -> UNIXSocketStream:
948
+ try:
949
+ return await connect_unix(self.path)
950
+ except OSError as exc:
951
+ raise ConnectionFailed(f"error connecting to {self.path!r}: {exc}") from exc
952
+
953
+
954
+ def as_connectable(
955
+ remote: ByteStreamConnectable
956
+ | tuple[str | IPv4Address | IPv6Address, int]
957
+ | str
958
+ | bytes
959
+ | PathLike[str],
960
+ /,
961
+ *,
962
+ tls: bool = False,
963
+ ssl_context: ssl.SSLContext | None = None,
964
+ tls_hostname: str | None = None,
965
+ tls_standard_compatible: bool = True,
966
+ ) -> ByteStreamConnectable:
967
+ """
968
+ Return a byte stream connectable from the given object.
969
+
970
+ If a bytestream connectable is given, it is returned unchanged.
971
+ If a tuple of (host, port) is given, a TCP connectable is returned.
972
+ If a string or bytes path is given, a UNIX connectable is returned.
973
+
974
+ If ``tls=True``, the connectable will be wrapped in a
975
+ :class:`~.streams.tls.TLSConnectable`.
976
+
977
+ :param remote: a connectable, a tuple of (host, port) or a path to a UNIX socket
978
+ :param tls: if ``True``, wrap the plaintext connectable in a
979
+ :class:`~.streams.tls.TLSConnectable`, using the provided TLS settings)
980
+ :param ssl_context: if ``tls=True``, the SSLContext object to use (if not provided,
981
+ a secure default will be created)
982
+ :param tls_hostname: if ``tls=True``, host name of the server to use for checking
983
+ the server certificate (defaults to the host portion of the address for TCP
984
+ connectables)
985
+ :param tls_standard_compatible: if ``False`` and ``tls=True``, makes the TLS stream
986
+ skip the closing handshake when closing the connection, so it won't raise an
987
+ exception if the server does the same
988
+
989
+ """
990
+ connectable: TCPConnectable | UNIXConnectable | TLSConnectable
991
+ if isinstance(remote, ByteStreamConnectable):
992
+ return remote
993
+ elif isinstance(remote, tuple) and len(remote) == 2:
994
+ connectable = TCPConnectable(*remote)
995
+ elif isinstance(remote, (str, bytes, PathLike)):
996
+ connectable = UNIXConnectable(remote)
997
+ else:
998
+ raise TypeError(f"cannot convert {remote!r} to a connectable")
999
+
1000
+ if tls:
1001
+ if not tls_hostname and isinstance(connectable, TCPConnectable):
1002
+ tls_hostname = str(connectable.host)
1003
+
1004
+ connectable = TLSConnectable(
1005
+ connectable,
1006
+ ssl_context=ssl_context,
1007
+ hostname=tls_hostname,
1008
+ standard_compatible=tls_standard_compatible,
1009
+ )
1010
+
1011
+ return connectable
.venv/lib/python3.13/site-packages/anyio/_core/_streams.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from typing import TypeVar
5
+ from warnings import warn
6
+
7
+ from ..streams.memory import (
8
+ MemoryObjectReceiveStream,
9
+ MemoryObjectSendStream,
10
+ _MemoryObjectStreamState,
11
+ )
12
+
13
+ T_Item = TypeVar("T_Item")
14
+
15
+
16
+ class create_memory_object_stream(
17
+ tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]],
18
+ ):
19
+ """
20
+ Create a memory object stream.
21
+
22
+ The stream's item type can be annotated like
23
+ :func:`create_memory_object_stream[T_Item]`.
24
+
25
+ :param max_buffer_size: number of items held in the buffer until ``send()`` starts
26
+ blocking
27
+ :param item_type: old way of marking the streams with the right generic type for
28
+ static typing (does nothing on AnyIO 4)
29
+
30
+ .. deprecated:: 4.0
31
+ Use ``create_memory_object_stream[YourItemType](...)`` instead.
32
+ :return: a tuple of (send stream, receive stream)
33
+
34
+ """
35
+
36
+ def __new__( # type: ignore[misc]
37
+ cls, max_buffer_size: float = 0, item_type: object = None
38
+ ) -> tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]]:
39
+ if max_buffer_size != math.inf and not isinstance(max_buffer_size, int):
40
+ raise ValueError("max_buffer_size must be either an integer or math.inf")
41
+ if max_buffer_size < 0:
42
+ raise ValueError("max_buffer_size cannot be negative")
43
+ if item_type is not None:
44
+ warn(
45
+ "The item_type argument has been deprecated in AnyIO 4.0. "
46
+ "Use create_memory_object_stream[YourItemType](...) instead.",
47
+ DeprecationWarning,
48
+ stacklevel=2,
49
+ )
50
+
51
+ state = _MemoryObjectStreamState[T_Item](max_buffer_size)
52
+ return (MemoryObjectSendStream(state), MemoryObjectReceiveStream(state))
.venv/lib/python3.13/site-packages/anyio/_core/_subprocesses.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import AsyncIterable, Iterable, Mapping, Sequence
4
+ from io import BytesIO
5
+ from os import PathLike
6
+ from subprocess import PIPE, CalledProcessError, CompletedProcess
7
+ from typing import IO, Any, TypeAlias, cast
8
+
9
+ from ..abc import Process
10
+ from ._eventloop import get_async_backend
11
+ from ._tasks import create_task_group
12
+
13
+ StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes]
14
+
15
+
16
+ async def run_process(
17
+ command: StrOrBytesPath | Sequence[StrOrBytesPath],
18
+ *,
19
+ input: bytes | None = None,
20
+ stdin: int | IO[Any] | None = None,
21
+ stdout: int | IO[Any] | None = PIPE,
22
+ stderr: int | IO[Any] | None = PIPE,
23
+ check: bool = True,
24
+ cwd: StrOrBytesPath | None = None,
25
+ env: Mapping[str, str] | None = None,
26
+ startupinfo: Any = None,
27
+ creationflags: int = 0,
28
+ start_new_session: bool = False,
29
+ pass_fds: Sequence[int] = (),
30
+ user: str | int | None = None,
31
+ group: str | int | None = None,
32
+ extra_groups: Iterable[str | int] | None = None,
33
+ umask: int = -1,
34
+ ) -> CompletedProcess[bytes]:
35
+ """
36
+ Run an external command in a subprocess and wait until it completes.
37
+
38
+ .. seealso:: :func:`subprocess.run`
39
+
40
+ :param command: either a string to pass to the shell, or an iterable of strings
41
+ containing the executable name or path and its arguments
42
+ :param input: bytes passed to the standard input of the subprocess
43
+ :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
44
+ a file-like object, or `None`; ``input`` overrides this
45
+ :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
46
+ a file-like object, or `None`
47
+ :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
48
+ :data:`subprocess.STDOUT`, a file-like object, or `None`
49
+ :param check: if ``True``, raise :exc:`~subprocess.CalledProcessError` if the
50
+ process terminates with a return code other than 0
51
+ :param cwd: If not ``None``, change the working directory to this before running the
52
+ command
53
+ :param env: if not ``None``, this mapping replaces the inherited environment
54
+ variables from the parent process
55
+ :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used
56
+ to specify process startup parameters (Windows only)
57
+ :param creationflags: flags that can be used to control the creation of the
58
+ subprocess (see :class:`subprocess.Popen` for the specifics)
59
+ :param start_new_session: if ``true`` the setsid() system call will be made in the
60
+ child process prior to the execution of the subprocess. (POSIX only)
61
+ :param pass_fds: sequence of file descriptors to keep open between the parent and
62
+ child processes. (POSIX only)
63
+ :param user: effective user to run the process as (Python >= 3.9, POSIX only)
64
+ :param group: effective group to run the process as (Python >= 3.9, POSIX only)
65
+ :param extra_groups: supplementary groups to set in the subprocess (Python >= 3.9,
66
+ POSIX only)
67
+ :param umask: if not negative, this umask is applied in the child process before
68
+ running the given command (Python >= 3.9, POSIX only)
69
+ :return: an object representing the completed process
70
+ :raises ~subprocess.CalledProcessError: if ``check`` is ``True`` and the process
71
+ exits with a nonzero return code
72
+
73
+ """
74
+
75
+ async def drain_stream(stream: AsyncIterable[bytes], index: int) -> None:
76
+ buffer = BytesIO()
77
+ async for chunk in stream:
78
+ buffer.write(chunk)
79
+
80
+ stream_contents[index] = buffer.getvalue()
81
+
82
+ if stdin is not None and input is not None:
83
+ raise ValueError("only one of stdin and input is allowed")
84
+
85
+ async with await open_process(
86
+ command,
87
+ stdin=PIPE if input else stdin,
88
+ stdout=stdout,
89
+ stderr=stderr,
90
+ cwd=cwd,
91
+ env=env,
92
+ startupinfo=startupinfo,
93
+ creationflags=creationflags,
94
+ start_new_session=start_new_session,
95
+ pass_fds=pass_fds,
96
+ user=user,
97
+ group=group,
98
+ extra_groups=extra_groups,
99
+ umask=umask,
100
+ ) as process:
101
+ stream_contents: list[bytes | None] = [None, None]
102
+ async with create_task_group() as tg:
103
+ if process.stdout:
104
+ tg.start_soon(drain_stream, process.stdout, 0)
105
+
106
+ if process.stderr:
107
+ tg.start_soon(drain_stream, process.stderr, 1)
108
+
109
+ if process.stdin and input:
110
+ await process.stdin.send(input)
111
+ await process.stdin.aclose()
112
+
113
+ await process.wait()
114
+
115
+ output, errors = stream_contents
116
+ if check and process.returncode != 0:
117
+ raise CalledProcessError(cast(int, process.returncode), command, output, errors)
118
+
119
+ return CompletedProcess(command, cast(int, process.returncode), output, errors)
120
+
121
+
122
+ async def open_process(
123
+ command: StrOrBytesPath | Sequence[StrOrBytesPath],
124
+ *,
125
+ stdin: int | IO[Any] | None = PIPE,
126
+ stdout: int | IO[Any] | None = PIPE,
127
+ stderr: int | IO[Any] | None = PIPE,
128
+ cwd: StrOrBytesPath | None = None,
129
+ env: Mapping[str, str] | None = None,
130
+ startupinfo: Any = None,
131
+ creationflags: int = 0,
132
+ start_new_session: bool = False,
133
+ pass_fds: Sequence[int] = (),
134
+ user: str | int | None = None,
135
+ group: str | int | None = None,
136
+ extra_groups: Iterable[str | int] | None = None,
137
+ umask: int = -1,
138
+ ) -> Process:
139
+ """
140
+ Start an external command in a subprocess.
141
+
142
+ .. seealso:: :class:`subprocess.Popen`
143
+
144
+ :param command: either a string to pass to the shell, or an iterable of strings
145
+ containing the executable name or path and its arguments
146
+ :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a
147
+ file-like object, or ``None``
148
+ :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
149
+ a file-like object, or ``None``
150
+ :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
151
+ :data:`subprocess.STDOUT`, a file-like object, or ``None``
152
+ :param cwd: If not ``None``, the working directory is changed before executing
153
+ :param env: If env is not ``None``, it must be a mapping that defines the
154
+ environment variables for the new process
155
+ :param creationflags: flags that can be used to control the creation of the
156
+ subprocess (see :class:`subprocess.Popen` for the specifics)
157
+ :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used
158
+ to specify process startup parameters (Windows only)
159
+ :param start_new_session: if ``true`` the setsid() system call will be made in the
160
+ child process prior to the execution of the subprocess. (POSIX only)
161
+ :param pass_fds: sequence of file descriptors to keep open between the parent and
162
+ child processes. (POSIX only)
163
+ :param user: effective user to run the process as (POSIX only)
164
+ :param group: effective group to run the process as (POSIX only)
165
+ :param extra_groups: supplementary groups to set in the subprocess (POSIX only)
166
+ :param umask: if not negative, this umask is applied in the child process before
167
+ running the given command (POSIX only)
168
+ :return: an asynchronous process object
169
+
170
+ """
171
+ kwargs: dict[str, Any] = {}
172
+ if user is not None:
173
+ kwargs["user"] = user
174
+
175
+ if group is not None:
176
+ kwargs["group"] = group
177
+
178
+ if extra_groups is not None:
179
+ kwargs["extra_groups"] = extra_groups
180
+
181
+ if umask >= 0:
182
+ kwargs["umask"] = umask
183
+
184
+ return await get_async_backend().open_process(
185
+ command,
186
+ stdin=stdin,
187
+ stdout=stdout,
188
+ stderr=stderr,
189
+ cwd=cwd,
190
+ env=env,
191
+ startupinfo=startupinfo,
192
+ creationflags=creationflags,
193
+ start_new_session=start_new_session,
194
+ pass_fds=pass_fds,
195
+ **kwargs,
196
+ )
.venv/lib/python3.13/site-packages/anyio/_core/_synchronization.py ADDED
@@ -0,0 +1,772 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from collections import deque
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass
7
+ from types import TracebackType
8
+ from typing import TypeVar
9
+
10
+ from ..lowlevel import checkpoint_if_cancelled
11
+ from ._eventloop import get_async_backend
12
+ from ._exceptions import BusyResourceError, NoEventLoopError
13
+ from ._tasks import CancelScope
14
+ from ._testing import TaskInfo, get_current_task
15
+
16
+ T = TypeVar("T")
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class EventStatistics:
21
+ """
22
+ :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Event.wait`
23
+ """
24
+
25
+ tasks_waiting: int
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class CapacityLimiterStatistics:
30
+ """
31
+ :ivar int borrowed_tokens: number of tokens currently borrowed by tasks
32
+ :ivar float total_tokens: total number of available tokens
33
+ :ivar tuple borrowers: tasks or other objects currently holding tokens borrowed from
34
+ this limiter
35
+ :ivar int tasks_waiting: number of tasks waiting on
36
+ :meth:`~.CapacityLimiter.acquire` or
37
+ :meth:`~.CapacityLimiter.acquire_on_behalf_of`
38
+ """
39
+
40
+ borrowed_tokens: int
41
+ total_tokens: float
42
+ borrowers: tuple[object, ...]
43
+ tasks_waiting: int
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class LockStatistics:
48
+ """
49
+ :ivar bool locked: flag indicating if this lock is locked or not
50
+ :ivar ~anyio.TaskInfo owner: task currently holding the lock (or ``None`` if the
51
+ lock is not held by any task)
52
+ :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Lock.acquire`
53
+ """
54
+
55
+ locked: bool
56
+ owner: TaskInfo | None
57
+ tasks_waiting: int
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class ConditionStatistics:
62
+ """
63
+ :ivar int tasks_waiting: number of tasks blocked on :meth:`~.Condition.wait`
64
+ :ivar ~anyio.LockStatistics lock_statistics: statistics of the underlying
65
+ :class:`~.Lock`
66
+ """
67
+
68
+ tasks_waiting: int
69
+ lock_statistics: LockStatistics
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class SemaphoreStatistics:
74
+ """
75
+ :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Semaphore.acquire`
76
+
77
+ """
78
+
79
+ tasks_waiting: int
80
+
81
+
82
+ class Event:
83
+ __slots__ = ("__weakref__",)
84
+
85
+ def __new__(cls) -> Event:
86
+ try:
87
+ return get_async_backend().create_event()
88
+ except NoEventLoopError:
89
+ return EventAdapter()
90
+
91
+ def set(self) -> None:
92
+ """Set the flag, notifying all listeners."""
93
+ raise NotImplementedError
94
+
95
+ def is_set(self) -> bool:
96
+ """Return ``True`` if the flag is set, ``False`` if not."""
97
+ raise NotImplementedError
98
+
99
+ async def wait(self) -> None:
100
+ """
101
+ Wait until the flag has been set.
102
+
103
+ If the flag has already been set when this method is called, it returns
104
+ immediately.
105
+
106
+ """
107
+ raise NotImplementedError
108
+
109
+ def statistics(self) -> EventStatistics:
110
+ """Return statistics about the current state of this event."""
111
+ raise NotImplementedError
112
+
113
+
114
+ class EventAdapter(Event):
115
+ __slots__ = "_internal_event", "_is_set"
116
+
117
+ def __new__(cls) -> EventAdapter:
118
+ return object.__new__(cls)
119
+
120
+ def __init__(self) -> None:
121
+ self._internal_event: Event | None = None
122
+ self._is_set = False
123
+
124
+ @property
125
+ def _event(self) -> Event:
126
+ if self._internal_event is None:
127
+ self._internal_event = get_async_backend().create_event()
128
+ if self._is_set:
129
+ self._internal_event.set()
130
+
131
+ return self._internal_event
132
+
133
+ def set(self) -> None:
134
+ if self._internal_event is None:
135
+ self._is_set = True
136
+ else:
137
+ self._event.set()
138
+
139
+ def is_set(self) -> bool:
140
+ if self._internal_event is None:
141
+ return self._is_set
142
+
143
+ return self._internal_event.is_set()
144
+
145
+ async def wait(self) -> None:
146
+ await self._event.wait()
147
+
148
+ def statistics(self) -> EventStatistics:
149
+ if self._internal_event is None:
150
+ return EventStatistics(tasks_waiting=0)
151
+
152
+ return self._internal_event.statistics()
153
+
154
+
155
+ class Lock:
156
+ __slots__ = ("__weakref__",)
157
+
158
+ def __new__(cls, *, fast_acquire: bool = False) -> Lock:
159
+ try:
160
+ return get_async_backend().create_lock(fast_acquire=fast_acquire)
161
+ except NoEventLoopError:
162
+ return LockAdapter(fast_acquire=fast_acquire)
163
+
164
+ async def __aenter__(self) -> None:
165
+ await self.acquire()
166
+
167
+ async def __aexit__(
168
+ self,
169
+ exc_type: type[BaseException] | None,
170
+ exc_val: BaseException | None,
171
+ exc_tb: TracebackType | None,
172
+ ) -> None:
173
+ self.release()
174
+
175
+ async def acquire(self) -> None:
176
+ """Acquire the lock."""
177
+ raise NotImplementedError
178
+
179
+ def acquire_nowait(self) -> None:
180
+ """
181
+ Acquire the lock, without blocking.
182
+
183
+ :raises ~anyio.WouldBlock: if the operation would block
184
+
185
+ """
186
+ raise NotImplementedError
187
+
188
+ def release(self) -> None:
189
+ """Release the lock."""
190
+ raise NotImplementedError
191
+
192
+ def locked(self) -> bool:
193
+ """Return True if the lock is currently held."""
194
+ raise NotImplementedError
195
+
196
+ def statistics(self) -> LockStatistics:
197
+ """
198
+ Return statistics about the current state of this lock.
199
+
200
+ .. versionadded:: 3.0
201
+ """
202
+ raise NotImplementedError
203
+
204
+
205
+ class LockAdapter(Lock):
206
+ __slots__ = "_internal_lock", "_fast_acquire"
207
+
208
+ def __new__(cls, *, fast_acquire: bool = False) -> LockAdapter:
209
+ return object.__new__(cls)
210
+
211
+ def __init__(self, *, fast_acquire: bool = False):
212
+ self._internal_lock: Lock | None = None
213
+ self._fast_acquire = fast_acquire
214
+
215
+ @property
216
+ def _lock(self) -> Lock:
217
+ if self._internal_lock is None:
218
+ self._internal_lock = get_async_backend().create_lock(
219
+ fast_acquire=self._fast_acquire
220
+ )
221
+
222
+ return self._internal_lock
223
+
224
+ async def __aenter__(self) -> None:
225
+ await self._lock.acquire()
226
+
227
+ async def __aexit__(
228
+ self,
229
+ exc_type: type[BaseException] | None,
230
+ exc_val: BaseException | None,
231
+ exc_tb: TracebackType | None,
232
+ ) -> None:
233
+ if self._internal_lock is not None:
234
+ self._internal_lock.release()
235
+
236
+ async def acquire(self) -> None:
237
+ """Acquire the lock."""
238
+ await self._lock.acquire()
239
+
240
+ def acquire_nowait(self) -> None:
241
+ """
242
+ Acquire the lock, without blocking.
243
+
244
+ :raises ~anyio.WouldBlock: if the operation would block
245
+
246
+ """
247
+ self._lock.acquire_nowait()
248
+
249
+ def release(self) -> None:
250
+ """Release the lock."""
251
+ self._lock.release()
252
+
253
+ def locked(self) -> bool:
254
+ """Return True if the lock is currently held."""
255
+ return self._lock.locked()
256
+
257
+ def statistics(self) -> LockStatistics:
258
+ """
259
+ Return statistics about the current state of this lock.
260
+
261
+ .. versionadded:: 3.0
262
+
263
+ """
264
+ if self._internal_lock is None:
265
+ return LockStatistics(False, None, 0)
266
+
267
+ return self._internal_lock.statistics()
268
+
269
+
270
+ class Condition:
271
+ __slots__ = "__weakref__", "_owner_task", "_lock", "_waiters"
272
+
273
+ def __init__(self, lock: Lock | None = None):
274
+ self._owner_task: TaskInfo | None = None
275
+ self._lock = lock or Lock()
276
+ self._waiters: deque[Event] = deque()
277
+
278
+ async def __aenter__(self) -> None:
279
+ await self.acquire()
280
+
281
+ async def __aexit__(
282
+ self,
283
+ exc_type: type[BaseException] | None,
284
+ exc_val: BaseException | None,
285
+ exc_tb: TracebackType | None,
286
+ ) -> None:
287
+ self.release()
288
+
289
+ def _check_acquired(self) -> None:
290
+ if self._owner_task != get_current_task():
291
+ raise RuntimeError("The current task is not holding the underlying lock")
292
+
293
+ async def acquire(self) -> None:
294
+ """Acquire the underlying lock."""
295
+ await self._lock.acquire()
296
+ self._owner_task = get_current_task()
297
+
298
+ def acquire_nowait(self) -> None:
299
+ """
300
+ Acquire the underlying lock, without blocking.
301
+
302
+ :raises ~anyio.WouldBlock: if the operation would block
303
+
304
+ """
305
+ self._lock.acquire_nowait()
306
+ self._owner_task = get_current_task()
307
+
308
+ def release(self) -> None:
309
+ """Release the underlying lock."""
310
+ self._lock.release()
311
+
312
+ def locked(self) -> bool:
313
+ """Return True if the lock is set."""
314
+ return self._lock.locked()
315
+
316
+ def notify(self, n: int = 1) -> None:
317
+ """Notify exactly n listeners."""
318
+ self._check_acquired()
319
+ for _ in range(n):
320
+ try:
321
+ event = self._waiters.popleft()
322
+ except IndexError:
323
+ break
324
+
325
+ event.set()
326
+
327
+ def notify_all(self) -> None:
328
+ """Notify all the listeners."""
329
+ self._check_acquired()
330
+ for event in self._waiters:
331
+ event.set()
332
+
333
+ self._waiters.clear()
334
+
335
+ async def wait(self) -> None:
336
+ """Wait for a notification."""
337
+ await checkpoint_if_cancelled()
338
+ self._check_acquired()
339
+ event = Event()
340
+ self._waiters.append(event)
341
+ self.release()
342
+ try:
343
+ await event.wait()
344
+ except BaseException:
345
+ if not event.is_set():
346
+ self._waiters.remove(event)
347
+ elif self._waiters:
348
+ # This task was notified by could not act on it, so pass
349
+ # it on to the next task
350
+ self._waiters.popleft().set()
351
+
352
+ raise
353
+ finally:
354
+ with CancelScope(shield=True):
355
+ await self.acquire()
356
+
357
+ async def wait_for(self, predicate: Callable[[], T]) -> T:
358
+ """
359
+ Wait until a predicate becomes true.
360
+
361
+ :param predicate: a callable that returns a truthy value when the condition is
362
+ met
363
+ :return: the result of the predicate
364
+
365
+ .. versionadded:: 4.11.0
366
+
367
+ """
368
+ while not (result := predicate()):
369
+ await self.wait()
370
+
371
+ return result
372
+
373
+ def statistics(self) -> ConditionStatistics:
374
+ """
375
+ Return statistics about the current state of this condition.
376
+
377
+ .. versionadded:: 3.0
378
+ """
379
+ return ConditionStatistics(len(self._waiters), self._lock.statistics())
380
+
381
+
382
+ class Semaphore:
383
+ __slots__ = "__weakref__", "_fast_acquire"
384
+
385
+ def __new__(
386
+ cls,
387
+ initial_value: int,
388
+ *,
389
+ max_value: int | None = None,
390
+ fast_acquire: bool = False,
391
+ ) -> Semaphore:
392
+ try:
393
+ return get_async_backend().create_semaphore(
394
+ initial_value, max_value=max_value, fast_acquire=fast_acquire
395
+ )
396
+ except NoEventLoopError:
397
+ return SemaphoreAdapter(initial_value, max_value=max_value)
398
+
399
+ def __init__(
400
+ self,
401
+ initial_value: int,
402
+ *,
403
+ max_value: int | None = None,
404
+ fast_acquire: bool = False,
405
+ ):
406
+ if not isinstance(initial_value, int):
407
+ raise TypeError("initial_value must be an integer")
408
+ if initial_value < 0:
409
+ raise ValueError("initial_value must be >= 0")
410
+ if max_value is not None:
411
+ if not isinstance(max_value, int):
412
+ raise TypeError("max_value must be an integer or None")
413
+ if max_value < initial_value:
414
+ raise ValueError(
415
+ "max_value must be equal to or higher than initial_value"
416
+ )
417
+
418
+ self._fast_acquire = fast_acquire
419
+
420
+ async def __aenter__(self) -> Semaphore:
421
+ await self.acquire()
422
+ return self
423
+
424
+ async def __aexit__(
425
+ self,
426
+ exc_type: type[BaseException] | None,
427
+ exc_val: BaseException | None,
428
+ exc_tb: TracebackType | None,
429
+ ) -> None:
430
+ self.release()
431
+
432
+ async def acquire(self) -> None:
433
+ """Decrement the semaphore value, blocking if necessary."""
434
+ raise NotImplementedError
435
+
436
+ def acquire_nowait(self) -> None:
437
+ """
438
+ Acquire the underlying lock, without blocking.
439
+
440
+ :raises ~anyio.WouldBlock: if the operation would block
441
+
442
+ """
443
+ raise NotImplementedError
444
+
445
+ def release(self) -> None:
446
+ """Increment the semaphore value."""
447
+ raise NotImplementedError
448
+
449
+ @property
450
+ def value(self) -> int:
451
+ """The current value of the semaphore."""
452
+ raise NotImplementedError
453
+
454
+ @property
455
+ def max_value(self) -> int | None:
456
+ """The maximum value of the semaphore."""
457
+ raise NotImplementedError
458
+
459
+ def statistics(self) -> SemaphoreStatistics:
460
+ """
461
+ Return statistics about the current state of this semaphore.
462
+
463
+ .. versionadded:: 3.0
464
+ """
465
+ raise NotImplementedError
466
+
467
+
468
+ class SemaphoreAdapter(Semaphore):
469
+ __slots__ = "_internal_semaphore", "_initial_value", "_max_value"
470
+
471
+ def __new__(
472
+ cls,
473
+ initial_value: int,
474
+ *,
475
+ max_value: int | None = None,
476
+ fast_acquire: bool = False,
477
+ ) -> SemaphoreAdapter:
478
+ return object.__new__(cls)
479
+
480
+ def __init__(
481
+ self,
482
+ initial_value: int,
483
+ *,
484
+ max_value: int | None = None,
485
+ fast_acquire: bool = False,
486
+ ) -> None:
487
+ super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire)
488
+ self._internal_semaphore: Semaphore | None = None
489
+ self._initial_value = initial_value
490
+ self._max_value = max_value
491
+
492
+ @property
493
+ def _semaphore(self) -> Semaphore:
494
+ if self._internal_semaphore is None:
495
+ self._internal_semaphore = get_async_backend().create_semaphore(
496
+ self._initial_value, max_value=self._max_value
497
+ )
498
+
499
+ return self._internal_semaphore
500
+
501
+ async def acquire(self) -> None:
502
+ await self._semaphore.acquire()
503
+
504
+ def acquire_nowait(self) -> None:
505
+ self._semaphore.acquire_nowait()
506
+
507
+ def release(self) -> None:
508
+ self._semaphore.release()
509
+
510
+ @property
511
+ def value(self) -> int:
512
+ if self._internal_semaphore is None:
513
+ return self._initial_value
514
+
515
+ return self._semaphore.value
516
+
517
+ @property
518
+ def max_value(self) -> int | None:
519
+ return self._max_value
520
+
521
+ def statistics(self) -> SemaphoreStatistics:
522
+ if self._internal_semaphore is None:
523
+ return SemaphoreStatistics(tasks_waiting=0)
524
+
525
+ return self._semaphore.statistics()
526
+
527
+
528
+ class CapacityLimiter:
529
+ __slots__ = ("__weakref__",)
530
+
531
+ def __new__(cls, total_tokens: float) -> CapacityLimiter:
532
+ try:
533
+ return get_async_backend().create_capacity_limiter(total_tokens)
534
+ except NoEventLoopError:
535
+ return CapacityLimiterAdapter(total_tokens)
536
+
537
+ async def __aenter__(self) -> None:
538
+ raise NotImplementedError
539
+
540
+ async def __aexit__(
541
+ self,
542
+ exc_type: type[BaseException] | None,
543
+ exc_val: BaseException | None,
544
+ exc_tb: TracebackType | None,
545
+ ) -> None:
546
+ raise NotImplementedError
547
+
548
+ @property
549
+ def total_tokens(self) -> float:
550
+ """
551
+ The total number of tokens available for borrowing.
552
+
553
+ This is a read-write property. If the total number of tokens is increased, the
554
+ proportionate number of tasks waiting on this limiter will be granted their
555
+ tokens.
556
+
557
+ .. versionchanged:: 3.0
558
+ The property is now writable.
559
+ .. versionchanged:: 4.12
560
+ The value can now be set to 0.
561
+
562
+ """
563
+ raise NotImplementedError
564
+
565
+ @total_tokens.setter
566
+ def total_tokens(self, value: float) -> None:
567
+ raise NotImplementedError
568
+
569
+ @property
570
+ def borrowed_tokens(self) -> int:
571
+ """The number of tokens that have currently been borrowed."""
572
+ raise NotImplementedError
573
+
574
+ @property
575
+ def available_tokens(self) -> float:
576
+ """The number of tokens currently available to be borrowed"""
577
+ raise NotImplementedError
578
+
579
+ def acquire_nowait(self) -> None:
580
+ """
581
+ Acquire a token for the current task without waiting for one to become
582
+ available.
583
+
584
+ :raises ~anyio.WouldBlock: if there are no tokens available for borrowing
585
+
586
+ """
587
+ raise NotImplementedError
588
+
589
+ def acquire_on_behalf_of_nowait(self, borrower: object) -> None:
590
+ """
591
+ Acquire a token without waiting for one to become available.
592
+
593
+ :param borrower: the entity borrowing a token
594
+ :raises ~anyio.WouldBlock: if there are no tokens available for borrowing
595
+
596
+ """
597
+ raise NotImplementedError
598
+
599
+ async def acquire(self) -> None:
600
+ """
601
+ Acquire a token for the current task, waiting if necessary for one to become
602
+ available.
603
+
604
+ """
605
+ raise NotImplementedError
606
+
607
+ async def acquire_on_behalf_of(self, borrower: object) -> None:
608
+ """
609
+ Acquire a token, waiting if necessary for one to become available.
610
+
611
+ :param borrower: the entity borrowing a token
612
+
613
+ """
614
+ raise NotImplementedError
615
+
616
+ def release(self) -> None:
617
+ """
618
+ Release the token held by the current task.
619
+
620
+ :raises RuntimeError: if the current task has not borrowed a token from this
621
+ limiter.
622
+
623
+ """
624
+ raise NotImplementedError
625
+
626
+ def release_on_behalf_of(self, borrower: object) -> None:
627
+ """
628
+ Release the token held by the given borrower.
629
+
630
+ :raises RuntimeError: if the borrower has not borrowed a token from this
631
+ limiter.
632
+
633
+ """
634
+ raise NotImplementedError
635
+
636
+ def statistics(self) -> CapacityLimiterStatistics:
637
+ """
638
+ Return statistics about the current state of this limiter.
639
+
640
+ .. versionadded:: 3.0
641
+
642
+ """
643
+ raise NotImplementedError
644
+
645
+
646
+ class CapacityLimiterAdapter(CapacityLimiter):
647
+ __slots__ = "_internal_limiter", "_total_tokens"
648
+
649
+ def __new__(cls, total_tokens: float) -> CapacityLimiterAdapter:
650
+ return object.__new__(cls)
651
+
652
+ def __init__(self, total_tokens: float) -> None:
653
+ self._internal_limiter: CapacityLimiter | None = None
654
+ self.total_tokens = total_tokens
655
+
656
+ @property
657
+ def _limiter(self) -> CapacityLimiter:
658
+ if self._internal_limiter is None:
659
+ self._internal_limiter = get_async_backend().create_capacity_limiter(
660
+ self._total_tokens
661
+ )
662
+
663
+ return self._internal_limiter
664
+
665
+ async def __aenter__(self) -> None:
666
+ await self._limiter.__aenter__()
667
+
668
+ async def __aexit__(
669
+ self,
670
+ exc_type: type[BaseException] | None,
671
+ exc_val: BaseException | None,
672
+ exc_tb: TracebackType | None,
673
+ ) -> None:
674
+ return await self._limiter.__aexit__(exc_type, exc_val, exc_tb)
675
+
676
+ @property
677
+ def total_tokens(self) -> float:
678
+ if self._internal_limiter is None:
679
+ return self._total_tokens
680
+
681
+ return self._internal_limiter.total_tokens
682
+
683
+ @total_tokens.setter
684
+ def total_tokens(self, value: float) -> None:
685
+ if not isinstance(value, int) and not math.isinf(value):
686
+ raise TypeError("total_tokens must be an int or math.inf")
687
+ elif value < 0:
688
+ raise ValueError("total_tokens must be >= 0")
689
+
690
+ if self._internal_limiter is None:
691
+ self._total_tokens = value
692
+ return
693
+
694
+ self._limiter.total_tokens = value
695
+
696
+ @property
697
+ def borrowed_tokens(self) -> int:
698
+ if self._internal_limiter is None:
699
+ return 0
700
+
701
+ return self._internal_limiter.borrowed_tokens
702
+
703
+ @property
704
+ def available_tokens(self) -> float:
705
+ if self._internal_limiter is None:
706
+ return self._total_tokens
707
+
708
+ return self._internal_limiter.available_tokens
709
+
710
+ def acquire_nowait(self) -> None:
711
+ self._limiter.acquire_nowait()
712
+
713
+ def acquire_on_behalf_of_nowait(self, borrower: object) -> None:
714
+ self._limiter.acquire_on_behalf_of_nowait(borrower)
715
+
716
+ async def acquire(self) -> None:
717
+ await self._limiter.acquire()
718
+
719
+ async def acquire_on_behalf_of(self, borrower: object) -> None:
720
+ await self._limiter.acquire_on_behalf_of(borrower)
721
+
722
+ def release(self) -> None:
723
+ self._limiter.release()
724
+
725
+ def release_on_behalf_of(self, borrower: object) -> None:
726
+ self._limiter.release_on_behalf_of(borrower)
727
+
728
+ def statistics(self) -> CapacityLimiterStatistics:
729
+ if self._internal_limiter is None:
730
+ return CapacityLimiterStatistics(
731
+ borrowed_tokens=0,
732
+ total_tokens=self.total_tokens,
733
+ borrowers=(),
734
+ tasks_waiting=0,
735
+ )
736
+
737
+ return self._internal_limiter.statistics()
738
+
739
+
740
+ class ResourceGuard:
741
+ """
742
+ A context manager for ensuring that a resource is only used by a single task at a
743
+ time.
744
+
745
+ Entering this context manager while the previous has not exited it yet will trigger
746
+ :exc:`BusyResourceError`.
747
+
748
+ :param action: the action to guard against (visible in the :exc:`BusyResourceError`
749
+ when triggered, e.g. "Another task is already {action} this resource")
750
+
751
+ .. versionadded:: 4.1
752
+ """
753
+
754
+ __slots__ = "__weakref__", "action", "_guarded"
755
+
756
+ def __init__(self, action: str = "using"):
757
+ self.action: str = action
758
+ self._guarded = False
759
+
760
+ def __enter__(self) -> None:
761
+ if self._guarded:
762
+ raise BusyResourceError(self.action)
763
+
764
+ self._guarded = True
765
+
766
+ def __exit__(
767
+ self,
768
+ exc_type: type[BaseException] | None,
769
+ exc_val: BaseException | None,
770
+ exc_tb: TracebackType | None,
771
+ ) -> None:
772
+ self._guarded = False
.venv/lib/python3.13/site-packages/anyio/_core/_tasks.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import sys
5
+ from collections.abc import (
6
+ Coroutine,
7
+ Generator,
8
+ )
9
+ from contextlib import (
10
+ contextmanager,
11
+ )
12
+ from enum import Enum, auto
13
+ from inspect import iscoroutine
14
+ from types import TracebackType
15
+ from typing import Any, Generic, final
16
+
17
+ from ..abc import TaskGroup, TaskStatus
18
+ from ._eventloop import get_async_backend, get_cancelled_exc_class
19
+ from ._exceptions import TaskCancelled, TaskFailed, TaskNotFinished
20
+
21
+ if sys.version_info >= (3, 13):
22
+ from typing import TypeVar
23
+ else:
24
+ from typing_extensions import TypeVar
25
+
26
+ if sys.version_info >= (3, 11):
27
+ from typing import Never, TypeVarTuple
28
+ else:
29
+ from typing_extensions import Never, TypeVarTuple
30
+
31
+ T = TypeVar("T")
32
+ T_co = TypeVar("T_co", covariant=True)
33
+ T_startval = TypeVar("T_startval", covariant=True, default=Never)
34
+ PosArgsT = TypeVarTuple("PosArgsT")
35
+
36
+
37
+ class _IgnoredTaskStatus(TaskStatus[object]):
38
+ def started(self, value: object = None) -> None:
39
+ pass
40
+
41
+
42
+ TASK_STATUS_IGNORED = _IgnoredTaskStatus()
43
+
44
+
45
+ class CancelScope:
46
+ """
47
+ Wraps a unit of work that can be made separately cancellable.
48
+
49
+ :param deadline: The time (clock value) when this scope is cancelled automatically
50
+ :param shield: ``True`` to shield the cancel scope from external cancellation
51
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
52
+ current thread
53
+ """
54
+
55
+ __slots__ = ("__weakref__",)
56
+
57
+ def __new__(
58
+ cls, *, deadline: float = math.inf, shield: bool = False
59
+ ) -> CancelScope:
60
+ return get_async_backend().create_cancel_scope(shield=shield, deadline=deadline)
61
+
62
+ def cancel(self, reason: str | None = None) -> None:
63
+ """
64
+ Cancel this scope immediately.
65
+
66
+ :param reason: a message describing the reason for the cancellation
67
+
68
+ """
69
+ raise NotImplementedError
70
+
71
+ @property
72
+ def deadline(self) -> float:
73
+ """
74
+ The time (clock value) when this scope is cancelled automatically.
75
+
76
+ Will be ``float('inf')`` if no timeout has been set.
77
+
78
+ """
79
+ raise NotImplementedError
80
+
81
+ @deadline.setter
82
+ def deadline(self, value: float) -> None:
83
+ raise NotImplementedError
84
+
85
+ @property
86
+ def cancel_called(self) -> bool:
87
+ """``True`` if :meth:`cancel` has been called."""
88
+ raise NotImplementedError
89
+
90
+ @property
91
+ def cancelled_caught(self) -> bool:
92
+ """
93
+ ``True`` if this scope suppressed a cancellation exception it itself raised.
94
+
95
+ This is typically used to check if any work was interrupted, or to see if the
96
+ scope was cancelled due to its deadline being reached. The value will, however,
97
+ only be ``True`` if the cancellation was triggered by the scope itself (and not
98
+ an outer scope).
99
+
100
+ """
101
+ raise NotImplementedError
102
+
103
+ @property
104
+ def shield(self) -> bool:
105
+ """
106
+ ``True`` if this scope is shielded from external cancellation.
107
+
108
+ While a scope is shielded, it will not receive cancellations from outside.
109
+
110
+ """
111
+ raise NotImplementedError
112
+
113
+ @shield.setter
114
+ def shield(self, value: bool) -> None:
115
+ raise NotImplementedError
116
+
117
+ def __enter__(self) -> CancelScope:
118
+ raise NotImplementedError
119
+
120
+ def __exit__(
121
+ self,
122
+ exc_type: type[BaseException] | None,
123
+ exc_val: BaseException | None,
124
+ exc_tb: TracebackType | None,
125
+ ) -> bool:
126
+ raise NotImplementedError
127
+
128
+
129
+ @contextmanager
130
+ def fail_after(
131
+ delay: float | None, shield: bool = False
132
+ ) -> Generator[CancelScope, None, None]:
133
+ """
134
+ Create a context manager which raises a :class:`TimeoutError` if does not finish in
135
+ time.
136
+
137
+ :param delay: maximum allowed time (in seconds) before raising the exception, or
138
+ ``None`` to disable the timeout
139
+ :param shield: ``True`` to shield the cancel scope from external cancellation
140
+ :return: a context manager that yields a cancel scope
141
+ :rtype: :class:`~typing.ContextManager`\\[:class:`~anyio.CancelScope`\\]
142
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
143
+ current thread
144
+
145
+ """
146
+ current_time = get_async_backend().current_time
147
+ deadline = (current_time() + delay) if delay is not None else math.inf
148
+ with get_async_backend().create_cancel_scope(
149
+ deadline=deadline, shield=shield
150
+ ) as cancel_scope:
151
+ yield cancel_scope
152
+
153
+ if cancel_scope.cancelled_caught and current_time() >= cancel_scope.deadline:
154
+ raise TimeoutError
155
+
156
+
157
+ def move_on_after(delay: float | None, shield: bool = False) -> CancelScope:
158
+ """
159
+ Create a cancel scope with a deadline that expires after the given delay.
160
+
161
+ :param delay: maximum allowed time (in seconds) before exiting the context block, or
162
+ ``None`` to disable the timeout
163
+ :param shield: ``True`` to shield the cancel scope from external cancellation
164
+ :return: a cancel scope
165
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
166
+ current thread
167
+
168
+ """
169
+ deadline = (
170
+ (get_async_backend().current_time() + delay) if delay is not None else math.inf
171
+ )
172
+ return get_async_backend().create_cancel_scope(deadline=deadline, shield=shield)
173
+
174
+
175
+ def current_effective_deadline() -> float:
176
+ """
177
+ Return the nearest deadline among all the cancel scopes effective for the current
178
+ task.
179
+
180
+ :return: a clock value from the event loop's internal clock (or ``float('inf')`` if
181
+ there is no deadline in effect, or ``float('-inf')`` if the current scope has
182
+ been cancelled)
183
+ :rtype: float
184
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
185
+ current thread
186
+
187
+ """
188
+ return get_async_backend().current_effective_deadline()
189
+
190
+
191
+ def create_task_group() -> TaskGroup:
192
+ """
193
+ Create a task group.
194
+
195
+ :return: a task group
196
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
197
+ current thread
198
+
199
+ """
200
+ return get_async_backend().create_task_group()
201
+
202
+
203
+ @final
204
+ class TaskHandle(Generic[T_co, T_startval]):
205
+ """
206
+ Returned from the task-spawning methods of :class:`TaskGroup`. Can be awaited on to
207
+ get the return value of the task (or the raised exception). If the task was
208
+ terminated by a :exc:`BaseException`, :exc:`TaskFailed` will be raised (or its
209
+ subclass :exc:`TaskCancelled` if the task was cancelled).
210
+
211
+ .. versionadded:: 4.14.0
212
+ """
213
+
214
+ class Status(Enum):
215
+ """
216
+ The status of a task handle.
217
+
218
+ .. attribute:: PENDING
219
+
220
+ The task has not finished yet.
221
+ .. attribute:: FINISHED
222
+
223
+ The task has finished with a return value.
224
+ .. attribute:: CANCELLING
225
+
226
+ The task has been cancelled but has not finished yet.
227
+ .. attribute:: CANCELLED
228
+
229
+ The task was cancelled and has finished since.
230
+ .. attribute:: FAILED
231
+
232
+ The task raised an exception.
233
+ """
234
+
235
+ PENDING = auto()
236
+ FINISHED = auto()
237
+ CANCELLING = auto()
238
+ CANCELLED = auto()
239
+ FAILED = auto()
240
+
241
+ __slots__ = (
242
+ "__weakref__",
243
+ "_coro",
244
+ "_name",
245
+ "_cancel_scope",
246
+ "_finished_event",
247
+ "_return_value",
248
+ "_start_value",
249
+ "_exception",
250
+ )
251
+
252
+ _return_value: T_co
253
+ _start_value: T_startval
254
+
255
+ def __init__(self, coro: Coroutine[Any, Any, T_co], name: object) -> None:
256
+ from ._synchronization import Event
257
+
258
+ self._coro = coro
259
+ self._cancel_scope = CancelScope()
260
+ self._finished_event = Event()
261
+ self._exception: BaseException | None = None
262
+
263
+ if name is not None:
264
+ self._name = str(name)
265
+ elif iscoroutine(coro):
266
+ self._name = coro.__qualname__
267
+ else:
268
+ self._name = str(coro) # coroutine-like object (e.g. asend() objects)
269
+
270
+ async def _run_coro(self) -> None:
271
+ __tracebackhide__ = True
272
+
273
+ with self._cancel_scope:
274
+ try:
275
+ retval = await self._coro
276
+ except BaseException as exc:
277
+ self._exception = exc
278
+ raise
279
+ else:
280
+ self._return_value = retval
281
+ finally:
282
+ self._finished_event.set()
283
+ del self # Break the reference cycle
284
+
285
+ def cancel(self) -> None:
286
+ """
287
+ Set the task to a cancelled state.
288
+
289
+ This will interrupt any interruptible asynchronous operation, and will cause
290
+ any further awaits on this task to get immediately cancelled, unless done in
291
+ a shielded cancel scope.
292
+
293
+ If the task has already finished, this method has no effect.
294
+ """
295
+ if not self._finished_event.is_set():
296
+ self._cancel_scope.cancel()
297
+
298
+ @property
299
+ def coro(self) -> Coroutine[Any, Any, T_co]:
300
+ """
301
+ The coroutine object that was passed to one of the task-spawning methods in
302
+ :class:`TaskGroup`.
303
+ """
304
+ return self._coro
305
+
306
+ @property
307
+ def status(self) -> TaskHandle.Status:
308
+ """
309
+ The current status of the task.
310
+
311
+ Every task starts in the :attr:`~TaskHandle.Status.PENDING` state.
312
+ If a task is cancelled while in this state, it will transition to the
313
+ :attr:`~TaskHandle.Status.CANCELLING` state. When the task finishes, it will
314
+ transition to one of the three final states (
315
+ :attr:`~TaskHandle.Status.FINISHED`, :attr:`~TaskHandle.Status.FAILED`, or
316
+ :attr:`~TaskHandle.Status.CANCELLING`) depending on the exception the task
317
+ raised, if any. No other status transitions will happen.
318
+ """
319
+ if not self._finished_event.is_set():
320
+ if self._cancel_scope.cancel_called:
321
+ return TaskHandle.Status.CANCELLING
322
+ else:
323
+ return TaskHandle.Status.PENDING
324
+ elif self._exception is not None:
325
+ if isinstance(self._exception, get_cancelled_exc_class()):
326
+ return TaskHandle.Status.CANCELLED
327
+ else:
328
+ return TaskHandle.Status.FAILED
329
+ else:
330
+ return TaskHandle.Status.FINISHED
331
+
332
+ @property
333
+ def name(self) -> str:
334
+ """The name of the task."""
335
+ return self._name
336
+
337
+ @property
338
+ def exception(self) -> BaseException | None:
339
+ """
340
+ The exception raised by the task, or ``None`` if it finished without raising.
341
+
342
+ :raises TaskNotFinished: if the task has not finished yet
343
+ :raises TaskCancelled: if the task was cancelled
344
+
345
+ """
346
+ match self.status:
347
+ case TaskHandle.Status.PENDING:
348
+ raise TaskNotFinished("the task has not finished yet")
349
+ case TaskHandle.Status.FINISHED:
350
+ return None
351
+ case TaskHandle.Status.CANCELLING:
352
+ raise TaskCancelled("the task was cancelled")
353
+ case TaskHandle.Status.CANCELLED:
354
+ raise TaskCancelled("the task was cancelled") from self._exception
355
+ case TaskHandle.Status.FAILED:
356
+ return self._exception
357
+
358
+ @property
359
+ def return_value(self) -> T_co:
360
+ """
361
+ The return value of the task.
362
+
363
+ :raises TaskNotFinished: if the task has not finished yet
364
+ :raises TaskCancelled: if the task was cancelled
365
+ :raises TaskFailed: if the task raised an exception
366
+
367
+ """
368
+ match self.status:
369
+ case TaskHandle.Status.PENDING:
370
+ raise TaskNotFinished("the task has not finished yet")
371
+ case TaskHandle.Status.FINISHED:
372
+ return self._return_value
373
+ case TaskHandle.Status.CANCELLING:
374
+ raise TaskCancelled("the task was cancelled")
375
+ case TaskHandle.Status.CANCELLED:
376
+ raise TaskCancelled("the task was cancelled") from self._exception
377
+ case TaskHandle.Status.FAILED:
378
+ raise TaskFailed("the task raised an exception") from self._exception
379
+
380
+ @property
381
+ def start_value(self) -> T_startval:
382
+ """
383
+ The value passed to :meth:`task_status.started() <.abc.TaskStatus.started>`,
384
+
385
+ :raises RuntimeError: if the task was not started with :meth:`TaskGroup.start()
386
+ <.abc.TaskGroup.start>`
387
+ """
388
+ try:
389
+ return self._start_value
390
+ except AttributeError:
391
+ raise RuntimeError(
392
+ "the task was not started with TaskGroup.start()"
393
+ ) from None
394
+
395
+ async def wait(self) -> None:
396
+ """
397
+ Wait for the task to finish.
398
+
399
+ This method will return as soon as the task has finished, no matter how it
400
+ happened.
401
+ """
402
+ await self._finished_event.wait()
403
+
404
+ def __await__(self) -> Generator[Any, Any, T_co]:
405
+ yield from self._finished_event.wait().__await__()
406
+ return self.return_value
407
+
408
+ def __repr__(self) -> str:
409
+ return (
410
+ f"<{self.__class__.__name__} {self.status.name.lower()} "
411
+ f"name={self._name!r} coro={self._coro!r}>"
412
+ )
.venv/lib/python3.13/site-packages/anyio/_core/_tempfile.py ADDED
@@ -0,0 +1,613 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ import tempfile
6
+ from collections.abc import Iterable
7
+ from io import BytesIO, TextIOWrapper
8
+ from types import TracebackType
9
+ from typing import (
10
+ TYPE_CHECKING,
11
+ Any,
12
+ AnyStr,
13
+ Generic,
14
+ overload,
15
+ )
16
+
17
+ from .. import to_thread
18
+ from .._core._fileio import AsyncFile
19
+ from ..lowlevel import checkpoint_if_cancelled
20
+
21
+ if TYPE_CHECKING:
22
+ from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer
23
+
24
+
25
+ class TemporaryFile(Generic[AnyStr]):
26
+ """
27
+ An asynchronous temporary file that is automatically created and cleaned up.
28
+
29
+ This class provides an asynchronous context manager interface to a temporary file.
30
+ The file is created using Python's standard `tempfile.TemporaryFile` function in a
31
+ background thread, and is wrapped as an asynchronous file using `AsyncFile`.
32
+
33
+ :param mode: The mode in which the file is opened. Defaults to "w+b".
34
+ :param buffering: The buffering policy (-1 means the default buffering).
35
+ :param encoding: The encoding used to decode or encode the file. Only applicable in
36
+ text mode.
37
+ :param newline: Controls how universal newlines mode works (only applicable in text
38
+ mode).
39
+ :param suffix: The suffix for the temporary file name.
40
+ :param prefix: The prefix for the temporary file name.
41
+ :param dir: The directory in which the temporary file is created.
42
+ :param errors: The error handling scheme used for encoding/decoding errors.
43
+ """
44
+
45
+ _async_file: AsyncFile[AnyStr]
46
+
47
+ @overload
48
+ def __init__(
49
+ self: TemporaryFile[bytes],
50
+ mode: OpenBinaryMode = ...,
51
+ buffering: int = ...,
52
+ encoding: str | None = ...,
53
+ newline: str | None = ...,
54
+ suffix: str | None = ...,
55
+ prefix: str | None = ...,
56
+ dir: str | None = ...,
57
+ *,
58
+ errors: str | None = ...,
59
+ ): ...
60
+ @overload
61
+ def __init__(
62
+ self: TemporaryFile[str],
63
+ mode: OpenTextMode,
64
+ buffering: int = ...,
65
+ encoding: str | None = ...,
66
+ newline: str | None = ...,
67
+ suffix: str | None = ...,
68
+ prefix: str | None = ...,
69
+ dir: str | None = ...,
70
+ *,
71
+ errors: str | None = ...,
72
+ ): ...
73
+
74
+ def __init__(
75
+ self,
76
+ mode: OpenTextMode | OpenBinaryMode = "w+b",
77
+ buffering: int = -1,
78
+ encoding: str | None = None,
79
+ newline: str | None = None,
80
+ suffix: str | None = None,
81
+ prefix: str | None = None,
82
+ dir: str | None = None,
83
+ *,
84
+ errors: str | None = None,
85
+ ) -> None:
86
+ self.mode = mode
87
+ self.buffering = buffering
88
+ self.encoding = encoding
89
+ self.newline = newline
90
+ self.suffix: str | None = suffix
91
+ self.prefix: str | None = prefix
92
+ self.dir: str | None = dir
93
+ self.errors = errors
94
+
95
+ async def __aenter__(self) -> AsyncFile[AnyStr]:
96
+ fp = await to_thread.run_sync(
97
+ lambda: tempfile.TemporaryFile(
98
+ self.mode,
99
+ self.buffering,
100
+ self.encoding,
101
+ self.newline,
102
+ self.suffix,
103
+ self.prefix,
104
+ self.dir,
105
+ errors=self.errors,
106
+ )
107
+ )
108
+ self._async_file = AsyncFile(fp)
109
+ return self._async_file
110
+
111
+ async def __aexit__(
112
+ self,
113
+ exc_type: type[BaseException] | None,
114
+ exc_value: BaseException | None,
115
+ traceback: TracebackType | None,
116
+ ) -> None:
117
+ await self._async_file.aclose()
118
+
119
+
120
+ class NamedTemporaryFile(Generic[AnyStr]):
121
+ """
122
+ An asynchronous named temporary file that is automatically created and cleaned up.
123
+
124
+ This class provides an asynchronous context manager for a temporary file with a
125
+ visible name in the file system. It uses Python's standard
126
+ :func:`~tempfile.NamedTemporaryFile` function and wraps the file object with
127
+ :class:`AsyncFile` for asynchronous operations.
128
+
129
+ :param mode: The mode in which the file is opened. Defaults to "w+b".
130
+ :param buffering: The buffering policy (-1 means the default buffering).
131
+ :param encoding: The encoding used to decode or encode the file. Only applicable in
132
+ text mode.
133
+ :param newline: Controls how universal newlines mode works (only applicable in text
134
+ mode).
135
+ :param suffix: The suffix for the temporary file name.
136
+ :param prefix: The prefix for the temporary file name.
137
+ :param dir: The directory in which the temporary file is created.
138
+ :param delete: Whether to delete the file when it is closed.
139
+ :param errors: The error handling scheme used for encoding/decoding errors.
140
+ :param delete_on_close: (Python 3.12+) Whether to delete the file on close.
141
+ """
142
+
143
+ _async_file: AsyncFile[AnyStr]
144
+
145
+ @overload
146
+ def __init__(
147
+ self: NamedTemporaryFile[bytes],
148
+ mode: OpenBinaryMode = ...,
149
+ buffering: int = ...,
150
+ encoding: str | None = ...,
151
+ newline: str | None = ...,
152
+ suffix: str | None = ...,
153
+ prefix: str | None = ...,
154
+ dir: str | None = ...,
155
+ delete: bool = ...,
156
+ *,
157
+ errors: str | None = ...,
158
+ delete_on_close: bool = ...,
159
+ ): ...
160
+ @overload
161
+ def __init__(
162
+ self: NamedTemporaryFile[str],
163
+ mode: OpenTextMode,
164
+ buffering: int = ...,
165
+ encoding: str | None = ...,
166
+ newline: str | None = ...,
167
+ suffix: str | None = ...,
168
+ prefix: str | None = ...,
169
+ dir: str | None = ...,
170
+ delete: bool = ...,
171
+ *,
172
+ errors: str | None = ...,
173
+ delete_on_close: bool = ...,
174
+ ): ...
175
+
176
+ def __init__(
177
+ self,
178
+ mode: OpenBinaryMode | OpenTextMode = "w+b",
179
+ buffering: int = -1,
180
+ encoding: str | None = None,
181
+ newline: str | None = None,
182
+ suffix: str | None = None,
183
+ prefix: str | None = None,
184
+ dir: str | None = None,
185
+ delete: bool = True,
186
+ *,
187
+ errors: str | None = None,
188
+ delete_on_close: bool = True,
189
+ ) -> None:
190
+ self._params: dict[str, Any] = {
191
+ "mode": mode,
192
+ "buffering": buffering,
193
+ "encoding": encoding,
194
+ "newline": newline,
195
+ "suffix": suffix,
196
+ "prefix": prefix,
197
+ "dir": dir,
198
+ "delete": delete,
199
+ "errors": errors,
200
+ }
201
+ if sys.version_info >= (3, 12):
202
+ self._params["delete_on_close"] = delete_on_close
203
+
204
+ async def __aenter__(self) -> AsyncFile[AnyStr]:
205
+ fp = await to_thread.run_sync(
206
+ lambda: tempfile.NamedTemporaryFile(**self._params)
207
+ )
208
+ self._async_file = AsyncFile(fp)
209
+ return self._async_file
210
+
211
+ async def __aexit__(
212
+ self,
213
+ exc_type: type[BaseException] | None,
214
+ exc_value: BaseException | None,
215
+ traceback: TracebackType | None,
216
+ ) -> None:
217
+ await self._async_file.aclose()
218
+
219
+
220
+ class SpooledTemporaryFile(AsyncFile[AnyStr]):
221
+ """
222
+ An asynchronous spooled temporary file that starts in memory and is spooled to disk.
223
+
224
+ This class provides an asynchronous interface to a spooled temporary file, much like
225
+ Python's standard :class:`~tempfile.SpooledTemporaryFile`. It supports asynchronous
226
+ write operations and provides a method to force a rollover to disk.
227
+
228
+ :param max_size: Maximum size in bytes before the file is rolled over to disk.
229
+ :param mode: The mode in which the file is opened. Defaults to "w+b".
230
+ :param buffering: The buffering policy (-1 means the default buffering).
231
+ :param encoding: The encoding used to decode or encode the file (text mode only).
232
+ :param newline: Controls how universal newlines mode works (text mode only).
233
+ :param suffix: The suffix for the temporary file name.
234
+ :param prefix: The prefix for the temporary file name.
235
+ :param dir: The directory in which the temporary file is created.
236
+ :param errors: The error handling scheme used for encoding/decoding errors.
237
+ """
238
+
239
+ _rolled: bool = False
240
+
241
+ @overload
242
+ def __init__(
243
+ self: SpooledTemporaryFile[bytes],
244
+ max_size: int = ...,
245
+ mode: OpenBinaryMode = ...,
246
+ buffering: int = ...,
247
+ encoding: str | None = ...,
248
+ newline: str | None = ...,
249
+ suffix: str | None = ...,
250
+ prefix: str | None = ...,
251
+ dir: str | None = ...,
252
+ *,
253
+ errors: str | None = ...,
254
+ ): ...
255
+ @overload
256
+ def __init__(
257
+ self: SpooledTemporaryFile[str],
258
+ max_size: int = ...,
259
+ mode: OpenTextMode = ...,
260
+ buffering: int = ...,
261
+ encoding: str | None = ...,
262
+ newline: str | None = ...,
263
+ suffix: str | None = ...,
264
+ prefix: str | None = ...,
265
+ dir: str | None = ...,
266
+ *,
267
+ errors: str | None = ...,
268
+ ): ...
269
+
270
+ def __init__(
271
+ self,
272
+ max_size: int = 0,
273
+ mode: OpenBinaryMode | OpenTextMode = "w+b",
274
+ buffering: int = -1,
275
+ encoding: str | None = None,
276
+ newline: str | None = None,
277
+ suffix: str | None = None,
278
+ prefix: str | None = None,
279
+ dir: str | None = None,
280
+ *,
281
+ errors: str | None = None,
282
+ ) -> None:
283
+ self._tempfile_params: dict[str, Any] = {
284
+ "mode": mode,
285
+ "buffering": buffering,
286
+ "encoding": encoding,
287
+ "newline": newline,
288
+ "suffix": suffix,
289
+ "prefix": prefix,
290
+ "dir": dir,
291
+ "errors": errors,
292
+ }
293
+ self._max_size = max_size
294
+ if "b" in mode:
295
+ super().__init__(BytesIO()) # type: ignore[arg-type]
296
+ else:
297
+ super().__init__(
298
+ TextIOWrapper( # type: ignore[arg-type]
299
+ BytesIO(),
300
+ encoding=encoding,
301
+ errors=errors,
302
+ newline=newline,
303
+ write_through=True,
304
+ )
305
+ )
306
+
307
+ async def aclose(self) -> None:
308
+ if not self._rolled:
309
+ self._fp.close()
310
+ return
311
+
312
+ await super().aclose()
313
+
314
+ async def _check(self) -> None:
315
+ if self._rolled or self._fp.tell() <= self._max_size:
316
+ return
317
+
318
+ await self.rollover()
319
+
320
+ async def rollover(self) -> None:
321
+ if self._rolled:
322
+ return
323
+
324
+ self._rolled = True
325
+ buffer = self._fp
326
+ buffer.seek(0)
327
+ self._fp = await to_thread.run_sync(
328
+ lambda: tempfile.TemporaryFile(**self._tempfile_params)
329
+ )
330
+ await self.write(buffer.read())
331
+ buffer.close()
332
+
333
+ @property
334
+ def closed(self) -> bool:
335
+ return self._fp.closed
336
+
337
+ async def read(self, size: int = -1) -> AnyStr:
338
+ if not self._rolled:
339
+ await checkpoint_if_cancelled()
340
+ return self._fp.read(size)
341
+
342
+ return await super().read(size) # type: ignore[return-value]
343
+
344
+ async def read1(self: SpooledTemporaryFile[bytes], size: int = -1) -> bytes:
345
+ if not self._rolled:
346
+ await checkpoint_if_cancelled()
347
+ return self._fp.read1(size)
348
+
349
+ return await super().read1(size)
350
+
351
+ async def readline(self) -> AnyStr:
352
+ if not self._rolled:
353
+ await checkpoint_if_cancelled()
354
+ return self._fp.readline()
355
+
356
+ return await super().readline() # type: ignore[return-value]
357
+
358
+ async def readlines(self) -> list[AnyStr]:
359
+ if not self._rolled:
360
+ await checkpoint_if_cancelled()
361
+ return self._fp.readlines()
362
+
363
+ return await super().readlines() # type: ignore[return-value]
364
+
365
+ async def readinto(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int:
366
+ if not self._rolled:
367
+ await checkpoint_if_cancelled()
368
+ self._fp.readinto(b)
369
+
370
+ return await super().readinto(b)
371
+
372
+ async def readinto1(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int:
373
+ if not self._rolled:
374
+ await checkpoint_if_cancelled()
375
+ self._fp.readinto(b)
376
+
377
+ return await super().readinto1(b)
378
+
379
+ async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int:
380
+ if not self._rolled:
381
+ await checkpoint_if_cancelled()
382
+ return self._fp.seek(offset, whence)
383
+
384
+ return await super().seek(offset, whence)
385
+
386
+ async def tell(self) -> int:
387
+ if not self._rolled:
388
+ await checkpoint_if_cancelled()
389
+ return self._fp.tell()
390
+
391
+ return await super().tell()
392
+
393
+ async def truncate(self, size: int | None = None) -> int:
394
+ if not self._rolled:
395
+ await checkpoint_if_cancelled()
396
+ return self._fp.truncate(size)
397
+
398
+ return await super().truncate(size)
399
+
400
+ @overload
401
+ async def write(self: SpooledTemporaryFile[bytes], b: ReadableBuffer) -> int: ...
402
+ @overload
403
+ async def write(self: SpooledTemporaryFile[str], b: str) -> int: ...
404
+
405
+ async def write(self, b: ReadableBuffer | str) -> int:
406
+ """
407
+ Asynchronously write data to the spooled temporary file.
408
+
409
+ If the file has not yet been rolled over, the data is written synchronously,
410
+ and a rollover is triggered if the size exceeds the maximum size.
411
+
412
+ :param s: The data to write.
413
+ :return: The number of bytes written.
414
+ :raises RuntimeError: If the underlying file is not initialized.
415
+
416
+ """
417
+ if not self._rolled:
418
+ await checkpoint_if_cancelled()
419
+ result = self._fp.write(b)
420
+ await self._check()
421
+ return result
422
+
423
+ return await super().write(b) # type: ignore[misc]
424
+
425
+ @overload
426
+ async def writelines(
427
+ self: SpooledTemporaryFile[bytes], lines: Iterable[ReadableBuffer]
428
+ ) -> None: ...
429
+ @overload
430
+ async def writelines(
431
+ self: SpooledTemporaryFile[str], lines: Iterable[str]
432
+ ) -> None: ...
433
+
434
+ async def writelines(self, lines: Iterable[str] | Iterable[ReadableBuffer]) -> None:
435
+ """
436
+ Asynchronously write a list of lines to the spooled temporary file.
437
+
438
+ If the file has not yet been rolled over, the lines are written synchronously,
439
+ and a rollover is triggered if the size exceeds the maximum size.
440
+
441
+ :param lines: An iterable of lines to write.
442
+ :raises RuntimeError: If the underlying file is not initialized.
443
+
444
+ """
445
+ if not self._rolled:
446
+ await checkpoint_if_cancelled()
447
+ result = self._fp.writelines(lines)
448
+ await self._check()
449
+ return result
450
+
451
+ return await super().writelines(lines) # type: ignore[misc]
452
+
453
+
454
+ class TemporaryDirectory(Generic[AnyStr]):
455
+ """
456
+ An asynchronous temporary directory that is created and cleaned up automatically.
457
+
458
+ This class provides an asynchronous context manager for creating a temporary
459
+ directory. It wraps Python's standard :class:`~tempfile.TemporaryDirectory` to
460
+ perform directory creation and cleanup operations in a background thread.
461
+
462
+ :param suffix: Suffix to be added to the temporary directory name.
463
+ :param prefix: Prefix to be added to the temporary directory name.
464
+ :param dir: The parent directory where the temporary directory is created.
465
+ :param ignore_cleanup_errors: Whether to ignore errors during cleanup
466
+ :param delete: Whether to delete the directory upon closing (Python 3.12+).
467
+ """
468
+
469
+ def __init__(
470
+ self,
471
+ suffix: AnyStr | None = None,
472
+ prefix: AnyStr | None = None,
473
+ dir: AnyStr | None = None,
474
+ *,
475
+ ignore_cleanup_errors: bool = False,
476
+ delete: bool = True,
477
+ ) -> None:
478
+ self.suffix: AnyStr | None = suffix
479
+ self.prefix: AnyStr | None = prefix
480
+ self.dir: AnyStr | None = dir
481
+ self.ignore_cleanup_errors = ignore_cleanup_errors
482
+ self.delete = delete
483
+
484
+ self._tempdir: tempfile.TemporaryDirectory | None = None
485
+
486
+ async def __aenter__(self) -> str:
487
+ params: dict[str, Any] = {
488
+ "suffix": self.suffix,
489
+ "prefix": self.prefix,
490
+ "dir": self.dir,
491
+ "ignore_cleanup_errors": self.ignore_cleanup_errors,
492
+ }
493
+ if sys.version_info >= (3, 12):
494
+ params["delete"] = self.delete
495
+
496
+ self._tempdir = await to_thread.run_sync(
497
+ lambda: tempfile.TemporaryDirectory(**params)
498
+ )
499
+ return await to_thread.run_sync(self._tempdir.__enter__)
500
+
501
+ async def __aexit__(
502
+ self,
503
+ exc_type: type[BaseException] | None,
504
+ exc_value: BaseException | None,
505
+ traceback: TracebackType | None,
506
+ ) -> None:
507
+ if self._tempdir is not None:
508
+ await to_thread.run_sync(
509
+ self._tempdir.__exit__, exc_type, exc_value, traceback
510
+ )
511
+
512
+ async def cleanup(self) -> None:
513
+ if self._tempdir is not None:
514
+ await to_thread.run_sync(self._tempdir.cleanup)
515
+
516
+
517
+ @overload
518
+ async def mkstemp(
519
+ suffix: str | None = None,
520
+ prefix: str | None = None,
521
+ dir: str | None = None,
522
+ text: bool = False,
523
+ ) -> tuple[int, str]: ...
524
+
525
+
526
+ @overload
527
+ async def mkstemp(
528
+ suffix: bytes | None = None,
529
+ prefix: bytes | None = None,
530
+ dir: bytes | None = None,
531
+ text: bool = False,
532
+ ) -> tuple[int, bytes]: ...
533
+
534
+
535
+ async def mkstemp(
536
+ suffix: AnyStr | None = None,
537
+ prefix: AnyStr | None = None,
538
+ dir: AnyStr | None = None,
539
+ text: bool = False,
540
+ ) -> tuple[int, str | bytes]:
541
+ """
542
+ Asynchronously create a temporary file and return an OS-level handle and the file
543
+ name.
544
+
545
+ This function wraps `tempfile.mkstemp` and executes it in a background thread.
546
+
547
+ :param suffix: Suffix to be added to the file name.
548
+ :param prefix: Prefix to be added to the file name.
549
+ :param dir: Directory in which the temporary file is created.
550
+ :param text: Whether the file is opened in text mode.
551
+ :return: A tuple containing the file descriptor and the file name.
552
+
553
+ """
554
+ return await to_thread.run_sync(tempfile.mkstemp, suffix, prefix, dir, text)
555
+
556
+
557
+ @overload
558
+ async def mkdtemp(
559
+ suffix: str | None = None,
560
+ prefix: str | None = None,
561
+ dir: str | None = None,
562
+ ) -> str: ...
563
+
564
+
565
+ @overload
566
+ async def mkdtemp(
567
+ suffix: bytes | None = None,
568
+ prefix: bytes | None = None,
569
+ dir: bytes | None = None,
570
+ ) -> bytes: ...
571
+
572
+
573
+ async def mkdtemp(
574
+ suffix: AnyStr | None = None,
575
+ prefix: AnyStr | None = None,
576
+ dir: AnyStr | None = None,
577
+ ) -> str | bytes:
578
+ """
579
+ Asynchronously create a temporary directory and return its path.
580
+
581
+ This function wraps `tempfile.mkdtemp` and executes it in a background thread.
582
+
583
+ :param suffix: Suffix to be added to the directory name.
584
+ :param prefix: Prefix to be added to the directory name.
585
+ :param dir: Parent directory where the temporary directory is created.
586
+ :return: The path of the created temporary directory.
587
+
588
+ """
589
+ return await to_thread.run_sync(tempfile.mkdtemp, suffix, prefix, dir)
590
+
591
+
592
+ async def gettempdir() -> str:
593
+ """
594
+ Asynchronously return the name of the directory used for temporary files.
595
+
596
+ This function wraps `tempfile.gettempdir` and executes it in a background thread.
597
+
598
+ :return: The path of the temporary directory as a string.
599
+
600
+ """
601
+ return await to_thread.run_sync(tempfile.gettempdir)
602
+
603
+
604
+ async def gettempdirb() -> bytes:
605
+ """
606
+ Asynchronously return the name of the directory used for temporary files in bytes.
607
+
608
+ This function wraps `tempfile.gettempdirb` and executes it in a background thread.
609
+
610
+ :return: The path of the temporary directory as bytes.
611
+
612
+ """
613
+ return await to_thread.run_sync(tempfile.gettempdirb)
.venv/lib/python3.13/site-packages/anyio/_core/_testing.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Awaitable, Generator
4
+ from typing import Any, cast
5
+
6
+ from ._eventloop import get_async_backend
7
+
8
+
9
+ class TaskInfo:
10
+ """
11
+ Represents an asynchronous task.
12
+
13
+ :ivar int id: the unique identifier of the task
14
+ :ivar parent_id: the identifier of the parent task, if any
15
+ :vartype parent_id: Optional[int]
16
+ :ivar str name: the description of the task (if any)
17
+ :ivar ~collections.abc.Coroutine coro: the coroutine object of the task
18
+ """
19
+
20
+ __slots__ = "_name", "id", "parent_id", "name", "coro"
21
+
22
+ def __init__(
23
+ self,
24
+ id: int,
25
+ parent_id: int | None,
26
+ name: str | None,
27
+ coro: Generator[Any, Any, Any] | Awaitable[Any],
28
+ ):
29
+ func = get_current_task
30
+ self._name = f"{func.__module__}.{func.__qualname__}"
31
+ self.id: int = id
32
+ self.parent_id: int | None = parent_id
33
+ self.name: str | None = name
34
+ self.coro: Generator[Any, Any, Any] | Awaitable[Any] = coro
35
+
36
+ def __eq__(self, other: object) -> bool:
37
+ if isinstance(other, TaskInfo):
38
+ return self.id == other.id
39
+
40
+ return NotImplemented
41
+
42
+ def __hash__(self) -> int:
43
+ return hash(self.id)
44
+
45
+ def __repr__(self) -> str:
46
+ return f"{self.__class__.__name__}(id={self.id!r}, name={self.name!r})"
47
+
48
+ def has_pending_cancellation(self) -> bool:
49
+ """
50
+ Return ``True`` if the task has a cancellation pending, ``False`` otherwise.
51
+
52
+ """
53
+ return False
54
+
55
+
56
+ def get_current_task() -> TaskInfo:
57
+ """
58
+ Return the current task.
59
+
60
+ :return: a representation of the current task
61
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
62
+ current thread
63
+
64
+ """
65
+ return get_async_backend().get_current_task()
66
+
67
+
68
+ def get_running_tasks() -> list[TaskInfo]:
69
+ """
70
+ Return a list of running tasks in the current event loop.
71
+
72
+ :return: a list of task info objects
73
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
74
+ current thread
75
+
76
+ """
77
+ return cast("list[TaskInfo]", get_async_backend().get_running_tasks())
78
+
79
+
80
+ async def wait_all_tasks_blocked() -> None:
81
+ """Wait until all other tasks are waiting for something."""
82
+ await get_async_backend().wait_all_tasks_blocked()
.venv/lib/python3.13/site-packages/anyio/_core/_typedattr.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable, Mapping
4
+ from typing import Any, TypeVar, final, overload
5
+
6
+ from ._exceptions import TypedAttributeLookupError
7
+
8
+ T_Attr = TypeVar("T_Attr")
9
+ T_Default = TypeVar("T_Default")
10
+ undefined = object()
11
+
12
+
13
+ def typed_attribute() -> Any:
14
+ """Return a unique object, used to mark typed attributes."""
15
+ return object()
16
+
17
+
18
+ class TypedAttributeSet:
19
+ """
20
+ Superclass for typed attribute collections.
21
+
22
+ Checks that every public attribute of every subclass has a type annotation.
23
+ """
24
+
25
+ def __init_subclass__(cls) -> None:
26
+ annotations: dict[str, Any] = getattr(cls, "__annotations__", {})
27
+ for attrname in dir(cls):
28
+ if not attrname.startswith("_") and attrname not in annotations:
29
+ raise TypeError(
30
+ f"Attribute {attrname!r} is missing its type annotation"
31
+ )
32
+
33
+ super().__init_subclass__()
34
+
35
+
36
+ class TypedAttributeProvider:
37
+ """Base class for classes that wish to provide typed extra attributes."""
38
+
39
+ @property
40
+ def extra_attributes(self) -> Mapping[T_Attr, Callable[[], T_Attr]]:
41
+ """
42
+ A mapping of the extra attributes to callables that return the corresponding
43
+ values.
44
+
45
+ If the provider wraps another provider, the attributes from that wrapper should
46
+ also be included in the returned mapping (but the wrapper may override the
47
+ callables from the wrapped instance).
48
+
49
+ """
50
+ return {}
51
+
52
+ @overload
53
+ def extra(self, attribute: T_Attr) -> T_Attr: ...
54
+
55
+ @overload
56
+ def extra(self, attribute: T_Attr, default: T_Default) -> T_Attr | T_Default: ...
57
+
58
+ @final
59
+ def extra(self, attribute: Any, default: object = undefined) -> object:
60
+ """
61
+ extra(attribute, default=undefined)
62
+
63
+ Return the value of the given typed extra attribute.
64
+
65
+ :param attribute: the attribute (member of a :class:`~TypedAttributeSet`) to
66
+ look for
67
+ :param default: the value that should be returned if no value is found for the
68
+ attribute
69
+ :raises ~anyio.TypedAttributeLookupError: if the search failed and no default
70
+ value was given
71
+
72
+ """
73
+ try:
74
+ getter = self.extra_attributes[attribute]
75
+ except KeyError:
76
+ if default is undefined:
77
+ raise TypedAttributeLookupError("Attribute not found") from None
78
+ else:
79
+ return default
80
+
81
+ return getter()