Ahmad2005 commited on
Commit
480a9ab
·
verified ·
1 Parent(s): 9a5496d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c +0 -0
  2. .cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c.body +88 -0
  3. .cache/pip/http-v2/0/4/4/7/c/0447ce2249fdae0f8cf52a43e01f215eacdf7c35d89a248bd4b4ebaa +0 -0
  4. .cache/pip/http-v2/0/4/4/7/c/0447ce2249fdae0f8cf52a43e01f215eacdf7c35d89a248bd4b4ebaa.body +0 -0
  5. .cache/pip/http-v2/2/6/9/6/f/2696f961349c363ba6eaa61f1f16df2705938f26ba64023adb039e90.body +0 -0
  6. .cache/pip/http-v2/5/2/e/b/0/52eb09ff78f469a17d2b7efae5a925d94693634f88d734649f34a875 +0 -0
  7. .cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b +0 -0
  8. .cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b.body +0 -0
  9. .cache/pip/http-v2/5/a/0/7/7/5a077ce3876f80d296a6957b033a784308127de6c24864c9c11a8eb9 +0 -0
  10. .cache/pip/http-v2/5/e/c/8/b/5ec8b58bc827caa12672b72c08527dbd1c5456edeea815f1e76cb526 +0 -0
  11. .cache/pip/http-v2/7/2/8/a/2/728a2f33f382f4dacf08f6df77aad6f3d889f819ba4fa3efad5ec7e4 +0 -0
  12. .cache/pip/http-v2/7/5/c/7/6/75c76ba3da983fc745a6549a0de110dcd624d42b682204260c21f535 +0 -0
  13. .cache/pip/http-v2/7/9/2/1/a/7921ac3318a5cdb592026cc26a94f7a2c1e1f7d3a1dc1e3857fd49f1.body +0 -0
  14. .cache/pip/http-v2/7/a/1/2/2/7a12234cc448f4452405e8d5b4447cba68049d0e6085f64225d7eef0 +0 -0
  15. .cache/pip/http-v2/7/a/1/2/2/7a12234cc448f4452405e8d5b4447cba68049d0e6085f64225d7eef0.body +592 -0
  16. .cache/pip/http-v2/7/f/f/b/a/7ffbaade46b578649cfc115650c307df3346f8f8e3d20f832aa9ec7b +0 -0
  17. .cache/pip/http-v2/8/1/8/8/f/8188f9db6169e57bb653240cc02c629488d0d899420b0725db0f7e4a +0 -0
  18. .cache/pip/http-v2/8/a/c/4/d/8ac4d14dc45e27d21da49fb515570b6f875b78707de9b08ce1088d1b +0 -0
  19. .cache/pip/http-v2/8/a/c/4/d/8ac4d14dc45e27d21da49fb515570b6f875b78707de9b08ce1088d1b.body +0 -0
  20. .cache/pip/http-v2/8/e/c/0/1/8ec01c6c0d8da8090ee14b669ee42a1879d3dc488903f676b506ef69 +0 -0
  21. .cache/pip/http-v2/8/e/c/0/1/8ec01c6c0d8da8090ee14b669ee42a1879d3dc488903f676b506ef69.body +87 -0
  22. .cache/pip/http-v2/8/f/0/a/d/8f0ad583652318494c12da41e4d30ff6225ec73d448a0754a0a7e898 +0 -0
  23. .cache/pip/http-v2/b/1/f/5/d/b1f5dc01896eee598e8915be35e61304ad2b16363d00711f8576642c +0 -0
  24. .cache/pip/http-v2/b/9/9/a/d/b99ad330dfd2e9e0337861ace33d07fca2ddfd480ba4473963ebc23d +0 -0
  25. .cache/pip/http-v2/f/1/9/c/b/f19cb9f2548ebec3162f98dc0753cc5fe07d32364a02b1720f376edb +0 -0
  26. .cache/pip/http-v2/f/1/9/c/b/f19cb9f2548ebec3162f98dc0753cc5fe07d32364a02b1720f376edb.body +0 -0
  27. .cache/pip/http-v2/f/6/4/9/7/f64975d28276977ea56e4922737def644a797957c860c54f5b5bc122 +0 -0
  28. .cache/pip/http-v2/f/6/4/9/7/f64975d28276977ea56e4922737def644a797957c860c54f5b5bc122.body +0 -0
  29. .cache/pip/http-v2/f/c/6/8/7/fc687abc6120c7bc7cfd867fe3788604e9f8e9dcf17e51396d803e25 +0 -0
  30. .cache/pip/http-v2/f/c/7/7/6/fc776fd0a9dd67f0a511e4cdeb9638db3cb4cdd09d04b821c1ec4c93 +0 -0
  31. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_backends/__init__.py +0 -0
  32. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_backends/_asyncio.py +0 -0
  33. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_backends/_trio.py +1468 -0
  34. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/__init__.py +0 -0
  35. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_asyncio_selector_thread.py +167 -0
  36. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_contextmanagers.py +200 -0
  37. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_eventloop.py +240 -0
  38. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_exceptions.py +177 -0
  39. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_fileio.py +960 -0
  40. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_resources.py +18 -0
  41. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_signals.py +29 -0
  42. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_sockets.py +1011 -0
  43. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_streams.py +52 -0
  44. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_subprocesses.py +196 -0
  45. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_synchronization.py +772 -0
  46. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_tasks.py +412 -0
  47. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_tempfile.py +613 -0
  48. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_testing.py +82 -0
  49. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/_typedattr.py +81 -0
  50. .cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/abc/__init__.py +58 -0
.cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c ADDED
Binary file (1.24 kB). View file
 
.cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c.body ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: Mako
3
+ Version: 1.3.12
4
+ Summary: A super-fast templating language that borrows the best ideas from the existing templating languages.
5
+ Home-page: https://www.makotemplates.org/
6
+ Author: Mike Bayer
7
+ Author-email: mike@zzzcomputing.com
8
+ License: MIT
9
+ Project-URL: Documentation, https://docs.makotemplates.org
10
+ Project-URL: Issue Tracker, https://github.com/sqlalchemy/mako
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Environment :: Web Environment
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: Implementation :: CPython
23
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
24
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
25
+ Requires-Python: >=3.8
26
+ Description-Content-Type: text/x-rst
27
+ License-File: LICENSE
28
+ Requires-Dist: MarkupSafe>=0.9.2
29
+ Provides-Extra: testing
30
+ Requires-Dist: pytest; extra == "testing"
31
+ Provides-Extra: babel
32
+ Requires-Dist: Babel; extra == "babel"
33
+ Provides-Extra: lingua
34
+ Requires-Dist: lingua; extra == "lingua"
35
+ Dynamic: license-file
36
+
37
+ =========================
38
+ Mako Templates for Python
39
+ =========================
40
+
41
+ Mako is a template library written in Python. It provides a familiar, non-XML
42
+ syntax which compiles into Python modules for maximum performance. Mako's
43
+ syntax and API borrows from the best ideas of many others, including Django
44
+ templates, Cheetah, Myghty, and Genshi. Conceptually, Mako is an embedded
45
+ Python (i.e. Python Server Page) language, which refines the familiar ideas
46
+ of componentized layout and inheritance to produce one of the most
47
+ straightforward and flexible models available, while also maintaining close
48
+ ties to Python calling and scoping semantics.
49
+
50
+ Nutshell
51
+ ========
52
+
53
+ ::
54
+
55
+ <%inherit file="base.html"/>
56
+ <%
57
+ rows = [[v for v in range(0,10)] for row in range(0,10)]
58
+ %>
59
+ <table>
60
+ % for row in rows:
61
+ ${makerow(row)}
62
+ % endfor
63
+ </table>
64
+
65
+ <%def name="makerow(row)">
66
+ <tr>
67
+ % for name in row:
68
+ <td>${name}</td>\
69
+ % endfor
70
+ </tr>
71
+ </%def>
72
+
73
+ Philosophy
74
+ ===========
75
+
76
+ Python is a great scripting language. Don't reinvent the wheel...your templates can handle it !
77
+
78
+ Documentation
79
+ ==============
80
+
81
+ See documentation for Mako at https://docs.makotemplates.org/en/latest/
82
+
83
+ License
84
+ ========
85
+
86
+ Mako is licensed under an MIT-style license (see LICENSE).
87
+ Other incorporated projects may be licensed under different licenses.
88
+ All licenses allow for non-commercial and commercial use.
.cache/pip/http-v2/0/4/4/7/c/0447ce2249fdae0f8cf52a43e01f215eacdf7c35d89a248bd4b4ebaa ADDED
Binary file (1.9 kB). View file
 
.cache/pip/http-v2/0/4/4/7/c/0447ce2249fdae0f8cf52a43e01f215eacdf7c35d89a248bd4b4ebaa.body ADDED
Binary file (21.3 kB). View file
 
.cache/pip/http-v2/2/6/9/6/f/2696f961349c363ba6eaa61f1f16df2705938f26ba64023adb039e90.body ADDED
Binary file (78.5 kB). View file
 
.cache/pip/http-v2/5/2/e/b/0/52eb09ff78f469a17d2b7efae5a925d94693634f88d734649f34a875 ADDED
Binary file (1.2 kB). View file
 
.cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b ADDED
Binary file (1.2 kB). View file
 
.cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b.body ADDED
Binary file (18.1 kB). View file
 
.cache/pip/http-v2/5/a/0/7/7/5a077ce3876f80d296a6957b033a784308127de6c24864c9c11a8eb9 ADDED
Binary file (1.22 kB). View file
 
.cache/pip/http-v2/5/e/c/8/b/5ec8b58bc827caa12672b72c08527dbd1c5456edeea815f1e76cb526 ADDED
Binary file (1.17 kB). View file
 
.cache/pip/http-v2/7/2/8/a/2/728a2f33f382f4dacf08f6df77aad6f3d889f819ba4fa3efad5ec7e4 ADDED
Binary file (1.9 kB). View file
 
.cache/pip/http-v2/7/5/c/7/6/75c76ba3da983fc745a6549a0de110dcd624d42b682204260c21f535 ADDED
Binary file (1.17 kB). View file
 
.cache/pip/http-v2/7/9/2/1/a/7921ac3318a5cdb592026cc26a94f7a2c1e1f7d3a1dc1e3857fd49f1.body ADDED
Binary file (1.94 kB). View file
 
.cache/pip/http-v2/7/a/1/2/2/7a12234cc448f4452405e8d5b4447cba68049d0e6085f64225d7eef0 ADDED
Binary file (1.21 kB). View file
 
.cache/pip/http-v2/7/a/1/2/2/7a12234cc448f4452405e8d5b4447cba68049d0e6085f64225d7eef0.body ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: timm
3
+ Version: 1.0.28
4
+ Summary: PyTorch Image Models
5
+ Keywords: pytorch,image-classification
6
+ Author-Email: Ross Wightman <ross@huggingface.co>
7
+ License: Apache-2.0
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Intended Audience :: Education
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Software Development
20
+ Classifier: Topic :: Software Development :: Libraries
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Project-URL: homepage, https://github.com/huggingface/pytorch-image-models
23
+ Project-URL: documentation, https://huggingface.co/docs/timm/en/index
24
+ Project-URL: repository, https://github.com/huggingface/pytorch-image-models
25
+ Requires-Python: >=3.8
26
+ Requires-Dist: torch
27
+ Requires-Dist: torchvision
28
+ Requires-Dist: pyyaml
29
+ Requires-Dist: huggingface_hub
30
+ Requires-Dist: safetensors
31
+ Description-Content-Type: text/markdown
32
+
33
+ # PyTorch Image Models
34
+ - [What's New](#whats-new)
35
+ - [Introduction](#introduction)
36
+ - [Models](#models)
37
+ - [Features](#features)
38
+ - [Results](#results)
39
+ - [Getting Started (Documentation)](#getting-started-documentation)
40
+ - [Train, Validation, Inference Scripts](#train-validation-inference-scripts)
41
+ - [Awesome PyTorch Resources](#awesome-pytorch-resources)
42
+ - [Licenses](#licenses)
43
+ - [Citing](#citing)
44
+
45
+ ## What's New
46
+
47
+ ## July 10, 2026
48
+ * Improve optimizer `torch.compile` and tensor learning-rate support.
49
+ * Extend NaFlexViT patch-layout (for NaFlex-CLAP), and `forward_intermediates` (NaFlex dict input) support.
50
+ * Harden pickle loading and improve custom-label inference.
51
+ * Release 1.0.28
52
+
53
+ ## May 27, 2026
54
+ * Add model defs and pretrained weights for EUPE ViT (DINOv3-style) and ConvNeXt models. See the [Efficient Universal Perception Encoder paper](https://arxiv.org/abs/2603.22387).
55
+ * Add TIPSv2 model defs and pretrained weights for (DINOv2-style) ViTs. See the [TIPSv2 paper](https://arxiv.org/abs/2604.12012).
56
+
57
+ ## May 8, 2026
58
+ * Release 1.0.27
59
+
60
+ ## April 23, 2026
61
+ * Add Gemma4 ViT encoders w/ NaFlex pipeline support (variable aspect/size per image). Thanks [Yonghye Kwon](https://github.com/developer0hye)
62
+ * Support DINOv3 weights in NaFlexVit. Thanks [Yonghye Kwon](https://github.com/developer0hye)
63
+ * Some improvements to Muon fallback (AdamW/NadamW) lr behavior
64
+
65
+ ## March 23, 2026
66
+ * Improve pickle checkpoint handling security. Default all loading to `weights_only=True`, add safe_global for ArgParse.
67
+ * Improve attention mask handling for core ViT/EVA models & layers. Resolve bool masks, pass `is_causal` through for SSL tasks.
68
+ * Fix class & register token uses with ViT and no pos embed enabled.
69
+ * Add Patch Representation Refinement (PRR) as a pooling option in ViT. Thanks Sina (https://github.com/sinahmr).
70
+ * Improve consistency of output projection / MLP dimensions for attention pooling layers.
71
+ * Hiera model F.SDPA optimization to allow Flash Attention kernel use.
72
+ * Caution added to SGDP optimizer.
73
+ * Release 1.0.26. First maintenance release since my departure from Hugging Face.
74
+
75
+ ## Feb 23, 2026
76
+ * Add token distillation training support to distillation task wrappers
77
+ * Remove some torch.jit usage in prep for official deprecation
78
+ * Caution added to AdamP optimizer
79
+ * Call reset_parameters() even if meta-device init so that buffers get init w/ hacks like init_empty_weights
80
+ * Tweak Muon optimizer to work with DTensor/FSDP2 (clamp_ instead of clamp_min_, alternate NS branch for DTensor)
81
+ * Release 1.0.25
82
+
83
+ ## Jan 21, 2026
84
+ * **Compat Break**: Fix oversight w/ QKV vs MLP bias in `ParallelScalingBlock` (& `DiffParallelScalingBlock`)
85
+ * Does not impact any trained `timm` models but could impact downstream use.
86
+
87
+ ## Jan 5 & 6, 2026
88
+ * Release 1.0.24
89
+ * Add new benchmark result csv files for inference timing on all models w/ RTX Pro 6000, 5090, and 4090 cards w/ PyTorch 2.9.1
90
+ * Fix moved module error in deprecated timm.models.layers import path that impacts legacy imports
91
+ * Release 1.0.23
92
+
93
+ ## Dec 30, 2025
94
+ * Add better NAdaMuon trained `dpwee`, `dwee`, `dlittle` (differential) ViTs with a small boost over previous runs
95
+ * https://huggingface.co/timm/vit_dlittle_patch16_reg1_gap_256.sbb_nadamuon_in1k (83.24% top-1)
96
+ * https://huggingface.co/timm/vit_dwee_patch16_reg1_gap_256.sbb_nadamuon_in1k (81.80% top-1)
97
+ * https://huggingface.co/timm/vit_dpwee_patch16_reg1_gap_256.sbb_nadamuon_in1k (81.67% top-1)
98
+ * Add a ~21M param `timm` variant of the CSATv2 model at 512x512 & 640x640
99
+ * https://huggingface.co/timm/csatv2_21m.sw_r640_in1k (83.13% top-1)
100
+ * https://huggingface.co/timm/csatv2_21m.sw_r512_in1k (82.58% top-1)
101
+ * Factor non-persistent param init out of `__init__` into a common method that can be externally called via `init_non_persistent_buffers()` after meta-device init.
102
+
103
+ ## Dec 12, 2025
104
+ * Add CSATV2 model (thanks https://github.com/gusdlf93) -- a lightweight but high res model with DCT stem & spatial attention. https://huggingface.co/Hyunil/CSATv2
105
+ * Add AdaMuon and NAdaMuon optimizer support to existing `timm` Muon impl. Appears more competitive vs AdamW with familiar hparams for image tasks.
106
+ * End of year PR cleanup, merge aspects of several long open PR
107
+ * Merge differential attention (`DiffAttention`), add corresponding `DiffParallelScalingBlock` (for ViT), train some wee vits
108
+ * https://huggingface.co/timm/vit_dwee_patch16_reg1_gap_256.sbb_in1k
109
+ * https://huggingface.co/timm/vit_dpwee_patch16_reg1_gap_256.sbb_in1k
110
+ * Add a few pooling modules, `LsePlus` and `SimPool`
111
+ * Cleanup, optimize `DropBlock2d` (also add support to ByobNet based models)
112
+ * Bump unit tests to PyTorch 2.9.1 + Python 3.13 on upper end, lower still PyTorch 1.13 + Python 3.10
113
+
114
+ ## Dec 1, 2025
115
+ * Add lightweight task abstraction, add logits and feature distillation support to train script via new tasks.
116
+ * Remove old APEX AMP support
117
+
118
+ ## Nov 4, 2025
119
+ * Fix LayerScale / LayerScale2d init bug (init values ignored), introduced in 1.0.21. Thanks https://github.com/Ilya-Fradlin
120
+ * Release 1.0.22
121
+
122
+ ## Oct 31, 2025 🎃
123
+ * Update imagenet & OOD variant result csv files to include a few new models and verify correctness over several torch & timm versions
124
+ * EfficientNet-X and EfficientNet-H B5 model weights added as part of a hparam search for AdamW vs Muon (still iterating on Muon runs)
125
+
126
+ ## Oct 16-20, 2025
127
+ * Add an impl of the Muon optimizer (based on https://github.com/KellerJordan/Muon) with customizations
128
+ * extra flexibility and improved handling for conv weights and fallbacks for weight shapes not suited for orthogonalization
129
+ * small speedup for NS iterations by reducing allocs and using fused (b)add(b)mm ops
130
+ * by default uses AdamW (or NAdamW if `nesterov=True`) updates if muon not suitable for parameter shape (or excluded via param group flag)
131
+ * like torch impl, select from several LR scale adjustment fns via `adjust_lr_fn`
132
+ * select from several NS coefficient presets or specify your own via `ns_coefficients`
133
+ * First 2 steps of 'meta' device model initialization supported
134
+ * Fix several ops that were breaking creation under 'meta' device context
135
+ * Add device & dtype factory kwarg support to all models and modules (anything inherting from nn.Module) in `timm`
136
+ * License fields added to pretrained cfgs in code
137
+ * Release 1.0.21
138
+
139
+ ## Sept 21, 2025
140
+ * Remap DINOv3 ViT weight tags from `lvd_1689m` -> `lvd1689m` to match (same for `sat_493m` -> `sat493m`)
141
+ * Release 1.0.20
142
+
143
+ ## Sept 17, 2025
144
+ * DINOv3 (https://arxiv.org/abs/2508.10104) ConvNeXt and ViT models added. ConvNeXt models were mapped to existing `timm` model. ViT support done via the EVA base model w/ a new `RotaryEmbeddingDinoV3` to match the DINOv3 specific RoPE impl
145
+ * HuggingFace Hub: https://huggingface.co/collections/timm/timm-dinov3-68cb08bb0bee365973d52a4d
146
+ * MobileCLIP-2 (https://arxiv.org/abs/2508.20691) vision encoders. New MCI3/MCI4 FastViT variants added and weights mapped to existing FastViT and B, L/14 ViTs.
147
+ * MetaCLIP-2 Worldwide (https://arxiv.org/abs/2507.22062) ViT encoder weights added.
148
+ * SigLIP-2 (https://arxiv.org/abs/2502.14786) NaFlex ViT encoder weights added via timm NaFlexViT model.
149
+ * Misc fixes and contributions
150
+
151
+ ## July 23, 2025
152
+ * Add `set_input_size()` method to EVA models, used by OpenCLIP 3.0.0 to allow resizing for timm based encoder models.
153
+ * Release 1.0.18, needed for PE-Core S & T models in OpenCLIP 3.0.0
154
+ * Fix small typing issue that broke Python 3.9 compat. 1.0.19 patch release.
155
+
156
+ ## July 21, 2025
157
+ * ROPE support added to NaFlexViT. All models covered by the EVA base (`eva.py`) including EVA, EVA02, Meta PE ViT, `timm` SBB ViT w/ ROPE, and Naver ROPE-ViT can be now loaded in NaFlexViT when `use_naflex=True` passed at model creation time
158
+ * More Meta PE ViT encoders added, including small/tiny variants, lang variants w/ tiling, and more spatial variants.
159
+ * PatchDropout fixed with NaFlexViT and also w/ EVA models (regression after adding Naver ROPE-ViT)
160
+ * Fix XY order with grid_indexing='xy', impacted non-square image use in 'xy' mode (only ROPE-ViT and PE impacted).
161
+
162
+ ## July 7, 2025
163
+ * MobileNet-v5 backbone tweaks for improved Google Gemma 3n behaviour (to pair with updated official weights)
164
+ * Add stem bias (zero'd in updated weights, compat break with old weights)
165
+ * GELU -> GELU (tanh approx). A minor change to be closer to JAX
166
+ * Add two arguments to layer-decay support, a min scale clamp and 'no optimization' scale threshold
167
+ * Add 'Fp32' LayerNorm, RMSNorm, SimpleNorm variants that can be enabled to force computation of norm in float32
168
+ * Some typing, argument cleanup for norm, norm+act layers done with above
169
+ * Support Naver ROPE-ViT (https://github.com/naver-ai/rope-vit) in `eva.py`, add RotaryEmbeddingMixed module for mixed mode, weights on HuggingFace Hub
170
+
171
+ |model |img_size|top1 |top5 |param_count|
172
+ |--------------------------------------------------|--------|------|------|-----------|
173
+ |vit_large_patch16_rope_mixed_ape_224.naver_in1k |224 |84.84 |97.122|304.4 |
174
+ |vit_large_patch16_rope_mixed_224.naver_in1k |224 |84.828|97.116|304.2 |
175
+ |vit_large_patch16_rope_ape_224.naver_in1k |224 |84.65 |97.154|304.37 |
176
+ |vit_large_patch16_rope_224.naver_in1k |224 |84.648|97.122|304.17 |
177
+ |vit_base_patch16_rope_mixed_ape_224.naver_in1k |224 |83.894|96.754|86.59 |
178
+ |vit_base_patch16_rope_mixed_224.naver_in1k |224 |83.804|96.712|86.44 |
179
+ |vit_base_patch16_rope_ape_224.naver_in1k |224 |83.782|96.61 |86.59 |
180
+ |vit_base_patch16_rope_224.naver_in1k |224 |83.718|96.672|86.43 |
181
+ |vit_small_patch16_rope_224.naver_in1k |224 |81.23 |95.022|21.98 |
182
+ |vit_small_patch16_rope_mixed_224.naver_in1k |224 |81.216|95.022|21.99 |
183
+ |vit_small_patch16_rope_ape_224.naver_in1k |224 |81.004|95.016|22.06 |
184
+ |vit_small_patch16_rope_mixed_ape_224.naver_in1k |224 |80.986|94.976|22.06 |
185
+ * Some cleanup of ROPE modules, helpers, and FX tracing leaf registration
186
+ * Preparing version 1.0.17 release
187
+
188
+ ## June 26, 2025
189
+ * MobileNetV5 backbone (w/ encoder only variant) for [Gemma 3n](https://ai.google.dev/gemma/docs/gemma-3n#parameters) image encoder
190
+ * Version 1.0.16 released
191
+
192
+ ## June 23, 2025
193
+ * Add F.grid_sample based 2D and factorized pos embed resize to NaFlexViT. Faster when lots of different sizes (based on example by https://github.com/stas-sl).
194
+ * Further speed up patch embed resample by replacing vmap with matmul (based on snippet by https://github.com/stas-sl).
195
+ * Add 3 initial native aspect NaFlexViT checkpoints created while testing, ImageNet-1k and 3 different pos embed configs w/ same hparams.
196
+
197
+ | Model | Top-1 Acc | Top-5 Acc | Params (M) | Eval Seq Len |
198
+ |:---|:---:|:---:|:---:|:---:|
199
+ | [naflexvit_base_patch16_par_gap.e300_s576_in1k](https://hf.co/timm/naflexvit_base_patch16_par_gap.e300_s576_in1k) | 83.67 | 96.45 | 86.63 | 576 |
200
+ | [naflexvit_base_patch16_parfac_gap.e300_s576_in1k](https://hf.co/timm/naflexvit_base_patch16_parfac_gap.e300_s576_in1k) | 83.63 | 96.41 | 86.46 | 576 |
201
+ | [naflexvit_base_patch16_gap.e300_s576_in1k](https://hf.co/timm/naflexvit_base_patch16_gap.e300_s576_in1k) | 83.50 | 96.46 | 86.63 | 576 |
202
+ * Support gradient checkpointing for `forward_intermediates` and fix some checkpointing bugs. Thanks https://github.com/brianhou0208
203
+ * Add 'corrected weight decay' (https://arxiv.org/abs/2506.02285) as option to AdamW (legacy), Adopt, Kron, Adafactor (BV), Lamb, LaProp, Lion, NadamW, RmsPropTF, SGDW optimizers
204
+ * Switch PE (perception encoder) ViT models to use native timm weights instead of remapping on the fly
205
+ * Fix cuda stream bug in prefetch loader
206
+
207
+ ## June 5, 2025
208
+ * Initial NaFlexVit model code. NaFlexVit is a Vision Transformer with:
209
+ 1. Encapsulated embedding and position encoding in a single module
210
+ 2. Support for nn.Linear patch embedding on pre-patchified (dictionary) inputs
211
+ 3. Support for NaFlex variable aspect, variable resolution (SigLip-2: https://arxiv.org/abs/2502.14786)
212
+ 4. Support for FlexiViT variable patch size (https://arxiv.org/abs/2212.08013)
213
+ 5. Support for NaViT fractional/factorized position embedding (https://arxiv.org/abs/2307.06304)
214
+ * Existing vit models in `vision_transformer.py` can be loaded into the NaFlexVit model by adding the `use_naflex=True` flag to `create_model`
215
+ * Some native weights coming soon
216
+ * A full NaFlex data pipeline is available that allows training / fine-tuning / evaluating with variable aspect / size images
217
+ * To enable in `train.py` and `validate.py` add the `--naflex-loader` arg, must be used with a NaFlexVit
218
+ * To evaluate an existing (classic) ViT loaded in NaFlexVit model w/ NaFlex data pipe:
219
+ * `python validate.py /imagenet --amp -j 8 --model vit_base_patch16_224 --model-kwargs use_naflex=True --naflex-loader --naflex-max-seq-len 256`
220
+ * The training has some extra args features worth noting
221
+ * The `--naflex-train-seq-lens'` argument specifies which sequence lengths to randomly pick from per batch during training
222
+ * The `--naflex-max-seq-len` argument sets the target sequence length for validation
223
+ * Adding `--model-kwargs enable_patch_interpolator=True --naflex-patch-sizes 12 16 24` will enable random patch size selection per-batch w/ interpolation
224
+ * The `--naflex-loss-scale` arg changes loss scaling mode per batch relative to the batch size, `timm` NaFlex loading changes the batch size for each seq len
225
+
226
+ ## May 28, 2025
227
+ * Add a number of small/fast models thanks to https://github.com/brianhou0208
228
+ * SwiftFormer - [(ICCV2023) SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications](https://github.com/Amshaker/SwiftFormer)
229
+ * FasterNet - [(CVPR2023) Run, Don’t Walk: Chasing Higher FLOPS for Faster Neural Networks](https://github.com/JierunChen/FasterNet)
230
+ * SHViT - [(CVPR2024) SHViT: Single-Head Vision Transformer with Memory Efficient](https://github.com/ysj9909/SHViT)
231
+ * StarNet - [(CVPR2024) Rewrite the Stars](https://github.com/ma-xu/Rewrite-the-Stars)
232
+ * GhostNet-V3 [GhostNetV3: Exploring the Training Strategies for Compact Models](https://github.com/huawei-noah/Efficient-AI-Backbones/tree/master/ghostnetv3_pytorch)
233
+ * Update EVA ViT (closest match) to support Perception Encoder models (https://arxiv.org/abs/2504.13181) from Meta, loading Hub weights but I still need to push dedicated `timm` weights
234
+ * Add some flexibility to ROPE impl
235
+ * Big increase in number of models supporting `forward_intermediates()` and some additional fixes thanks to https://github.com/brianhou0208
236
+ * DaViT, EdgeNeXt, EfficientFormerV2, EfficientViT(MIT), EfficientViT(MSRA), FocalNet, GCViT, HGNet /V2, InceptionNeXt, Inception-V4, MambaOut, MetaFormer, NesT, Next-ViT, PiT, PVT V2, RepGhostNet, RepViT, ResNetV2, ReXNet, TinyViT, TResNet, VoV
237
+ * TNT model updated w/ new weights `forward_intermediates()` thanks to https://github.com/brianhou0208
238
+ * Add `local-dir:` pretrained schema, can use `local-dir:/path/to/model/folder` for model name to source model / pretrained cfg & weights Hugging Face Hub models (config.json + weights file) from a local folder.
239
+ * Fixes, improvements for onnx export
240
+
241
+ ## Feb 21, 2025
242
+ * SigLIP 2 ViT image encoders added (https://huggingface.co/collections/timm/siglip-2-67b8e72ba08b09dd97aecaf9)
243
+ * Variable resolution / aspect NaFlex versions are a WIP
244
+ * Add 'SO150M2' ViT weights trained with SBB recipes, great results, better for ImageNet than previous attempt w/ less training.
245
+ * `vit_so150m2_patch16_reg1_gap_448.sbb_e200_in12k_ft_in1k` - 88.1% top-1
246
+ * `vit_so150m2_patch16_reg1_gap_384.sbb_e200_in12k_ft_in1k` - 87.9% top-1
247
+ * `vit_so150m2_patch16_reg1_gap_256.sbb_e200_in12k_ft_in1k` - 87.3% top-1
248
+ * `vit_so150m2_patch16_reg4_gap_256.sbb_e200_in12k`
249
+ * Updated InternViT-300M '2.5' weights
250
+ * Release 1.0.15
251
+
252
+ ## Feb 1, 2025
253
+ * FYI PyTorch 2.6 & Python 3.13 are tested and working w/ current main and released version of `timm`
254
+
255
+ ## Jan 27, 2025
256
+ * Add Kron Optimizer (PSGD w/ Kronecker-factored preconditioner)
257
+ * Code from https://github.com/evanatyourservice/kron_torch
258
+ * See also https://sites.google.com/site/lixilinx/home/psgd
259
+
260
+ ## Jan 19, 2025
261
+ * Fix loading of LeViT safetensor weights, remove conversion code which should have been deactivated
262
+ * Add 'SO150M' ViT weights trained with SBB recipes, decent results, but not optimal shape for ImageNet-12k/1k pretrain/ft
263
+ * `vit_so150m_patch16_reg4_gap_256.sbb_e250_in12k_ft_in1k` - 86.7% top-1
264
+ * `vit_so150m_patch16_reg4_gap_384.sbb_e250_in12k_ft_in1k` - 87.4% top-1
265
+ * `vit_so150m_patch16_reg4_gap_256.sbb_e250_in12k`
266
+ * Misc typing, typo, etc. cleanup
267
+ * 1.0.14 release to get above LeViT fix out
268
+
269
+ ## Jan 9, 2025
270
+ * Add support to train and validate in pure `bfloat16` or `float16`
271
+ * `wandb` project name arg added by https://github.com/caojiaolong, use arg.experiment for name
272
+ * Fix old issue w/ checkpoint saving not working on filesystem w/o hard-link support (e.g. FUSE fs mounts)
273
+ * 1.0.13 release
274
+
275
+ ## Jan 6, 2025
276
+ * Add `torch.utils.checkpoint.checkpoint()` wrapper in `timm.models` that defaults `use_reentrant=False`, unless `TIMM_REENTRANT_CKPT=1` is set in env.
277
+
278
+ ## Dec 31, 2024
279
+ * `convnext_nano` 384x384 ImageNet-12k pretrain & fine-tune. https://huggingface.co/models?search=convnext_nano%20r384
280
+ * Add AIM-v2 encoders from https://github.com/apple/ml-aim, see on Hub: https://huggingface.co/models?search=timm%20aimv2
281
+ * Add PaliGemma2 encoders from https://github.com/google-research/big_vision to existing PaliGemma, see on Hub: https://huggingface.co/models?search=timm%20pali2
282
+ * Add missing L/14 DFN2B 39B CLIP ViT, `vit_large_patch14_clip_224.dfn2b_s39b`
283
+ * Fix existing `RmsNorm` layer & fn to match standard formulation, use PT 2.5 impl when possible. Move old impl to `SimpleNorm` layer, it's LN w/o centering or bias. There were only two `timm` models using it, and they have been updated.
284
+ * Allow override of `cache_dir` arg for model creation
285
+ * Pass through `trust_remote_code` for HF datasets wrapper
286
+ * `inception_next_atto` model added by creator
287
+ * Adan optimizer caution, and Lamb decoupled weight decay options
288
+ * Some feature_info metadata fixed by https://github.com/brianhou0208
289
+ * All OpenCLIP and JAX (CLIP, SigLIP, Pali, etc) model weights that used load time remapping were given their own HF Hub instances so that they work with `hf-hub:` based loading, and thus will work with new Transformers `TimmWrapperModel`
290
+
291
+ ## Introduction
292
+
293
+ Py**T**orch **Im**age **M**odels (`timm`) is a collection of image models, layers, utilities, optimizers, schedulers, data-loaders / augmentations, and reference training / validation scripts that aim to pull together a wide variety of SOTA models with ability to reproduce ImageNet training results.
294
+
295
+ The work of many others is present here. I've tried to make sure all source material is acknowledged via links to github, arxiv papers, etc in the README, documentation, and code docstrings. Please let me know if I missed anything.
296
+
297
+ ## Features
298
+
299
+ ### Models
300
+
301
+ All model architecture families include variants with pretrained weights. There are specific model variants without any weights, it is NOT a bug. Help training new or better weights is always appreciated.
302
+
303
+ * Aggregating Nested Transformers - https://arxiv.org/abs/2105.12723
304
+ * BEiT - https://arxiv.org/abs/2106.08254
305
+ * BEiT-V2 - https://arxiv.org/abs/2208.06366
306
+ * BEiT3 - https://arxiv.org/abs/2208.10442
307
+ * Big Transfer ResNetV2 (BiT) - https://arxiv.org/abs/1912.11370
308
+ * Bottleneck Transformers - https://arxiv.org/abs/2101.11605
309
+ * CaiT (Class-Attention in Image Transformers) - https://arxiv.org/abs/2103.17239
310
+ * CoaT (Co-Scale Conv-Attentional Image Transformers) - https://arxiv.org/abs/2104.06399
311
+ * CoAtNet (Convolution and Attention) - https://arxiv.org/abs/2106.04803
312
+ * ConvNeXt - https://arxiv.org/abs/2201.03545
313
+ * ConvNeXt-V2 - http://arxiv.org/abs/2301.00808
314
+ * ConViT (Soft Convolutional Inductive Biases Vision Transformers)- https://arxiv.org/abs/2103.10697
315
+ * CspNet (Cross-Stage Partial Networks) - https://arxiv.org/abs/1911.11929
316
+ * DeiT - https://arxiv.org/abs/2012.12877
317
+ * DeiT-III - https://arxiv.org/pdf/2204.07118.pdf
318
+ * DenseNet - https://arxiv.org/abs/1608.06993
319
+ * DLA - https://arxiv.org/abs/1707.06484
320
+ * DPN (Dual-Path Network) - https://arxiv.org/abs/1707.01629
321
+ * EdgeNeXt - https://arxiv.org/abs/2206.10589
322
+ * EfficientFormer - https://arxiv.org/abs/2206.01191
323
+ * EfficientFormer-V2 - https://arxiv.org/abs/2212.08059
324
+ * EfficientNet (MBConvNet Family)
325
+ * EfficientNet NoisyStudent (B0-B7, L2) - https://arxiv.org/abs/1911.04252
326
+ * EfficientNet AdvProp (B0-B8) - https://arxiv.org/abs/1911.09665
327
+ * EfficientNet (B0-B7) - https://arxiv.org/abs/1905.11946
328
+ * EfficientNet-EdgeTPU (S, M, L) - https://ai.googleblog.com/2019/08/efficientnet-edgetpu-creating.html
329
+ * EfficientNet V2 - https://arxiv.org/abs/2104.00298
330
+ * FBNet-C - https://arxiv.org/abs/1812.03443
331
+ * MixNet - https://arxiv.org/abs/1907.09595
332
+ * MNASNet B1, A1 (Squeeze-Excite), and Small - https://arxiv.org/abs/1807.11626
333
+ * MobileNet-V2 - https://arxiv.org/abs/1801.04381
334
+ * Single-Path NAS - https://arxiv.org/abs/1904.02877
335
+ * TinyNet - https://arxiv.org/abs/2010.14819
336
+ * EfficientViT (MIT) - https://arxiv.org/abs/2205.14756
337
+ * EfficientViT (MSRA) - https://arxiv.org/abs/2305.07027
338
+ * EVA - https://arxiv.org/abs/2211.07636
339
+ * EVA-02 - https://arxiv.org/abs/2303.11331
340
+ * FasterNet - https://arxiv.org/abs/2303.03667
341
+ * FastViT - https://arxiv.org/abs/2303.14189
342
+ * FlexiViT - https://arxiv.org/abs/2212.08013
343
+ * FocalNet (Focal Modulation Networks) - https://arxiv.org/abs/2203.11926
344
+ * GCViT (Global Context Vision Transformer) - https://arxiv.org/abs/2206.09959
345
+ * GhostNet - https://arxiv.org/abs/1911.11907
346
+ * GhostNet-V2 - https://arxiv.org/abs/2211.12905
347
+ * GhostNet-V3 - https://arxiv.org/abs/2404.11202
348
+ * gMLP - https://arxiv.org/abs/2105.08050
349
+ * GPU-Efficient Networks - https://arxiv.org/abs/2006.14090
350
+ * Halo Nets - https://arxiv.org/abs/2103.12731
351
+ * HGNet / HGNet-V2 - TBD
352
+ * HRNet - https://arxiv.org/abs/1908.07919
353
+ * InceptionNeXt - https://arxiv.org/abs/2303.16900
354
+ * Inception-V3 - https://arxiv.org/abs/1512.00567
355
+ * Inception-ResNet-V2 and Inception-V4 - https://arxiv.org/abs/1602.07261
356
+ * Lambda Networks - https://arxiv.org/abs/2102.08602
357
+ * LeViT (Vision Transformer in ConvNet's Clothing) - https://arxiv.org/abs/2104.01136
358
+ * MambaOut - https://arxiv.org/abs/2405.07992
359
+ * MaxViT (Multi-Axis Vision Transformer) - https://arxiv.org/abs/2204.01697
360
+ * MetaFormer (PoolFormer-v2, ConvFormer, CAFormer) - https://arxiv.org/abs/2210.13452
361
+ * MLP-Mixer - https://arxiv.org/abs/2105.01601
362
+ * MobileCLIP - https://arxiv.org/abs/2311.17049
363
+ * MobileNet-V3 (MBConvNet w/ Efficient Head) - https://arxiv.org/abs/1905.02244
364
+ * FBNet-V3 - https://arxiv.org/abs/2006.02049
365
+ * HardCoRe-NAS - https://arxiv.org/abs/2102.11646
366
+ * LCNet - https://arxiv.org/abs/2109.15099
367
+ * MobileNetV4 - https://arxiv.org/abs/2404.10518
368
+ * MobileOne - https://arxiv.org/abs/2206.04040
369
+ * MobileViT - https://arxiv.org/abs/2110.02178
370
+ * MobileViT-V2 - https://arxiv.org/abs/2206.02680
371
+ * MViT-V2 (Improved Multiscale Vision Transformer) - https://arxiv.org/abs/2112.01526
372
+ * NASNet-A - https://arxiv.org/abs/1707.07012
373
+ * NesT - https://arxiv.org/abs/2105.12723
374
+ * Next-ViT - https://arxiv.org/abs/2207.05501
375
+ * NFNet-F - https://arxiv.org/abs/2102.06171
376
+ * NF-RegNet / NF-ResNet - https://arxiv.org/abs/2101.08692
377
+ * PE (Perception Encoder) - https://arxiv.org/abs/2504.13181
378
+ * PNasNet - https://arxiv.org/abs/1712.00559
379
+ * PoolFormer (MetaFormer) - https://arxiv.org/abs/2111.11418
380
+ * Pooling-based Vision Transformer (PiT) - https://arxiv.org/abs/2103.16302
381
+ * PVT-V2 (Improved Pyramid Vision Transformer) - https://arxiv.org/abs/2106.13797
382
+ * RDNet (DenseNets Reloaded) - https://arxiv.org/abs/2403.19588
383
+ * RegNet - https://arxiv.org/abs/2003.13678
384
+ * RegNetZ - https://arxiv.org/abs/2103.06877
385
+ * RepVGG - https://arxiv.org/abs/2101.03697
386
+ * RepGhostNet - https://arxiv.org/abs/2211.06088
387
+ * RepViT - https://arxiv.org/abs/2307.09283
388
+ * ResMLP - https://arxiv.org/abs/2105.03404
389
+ * ResNet/ResNeXt
390
+ * ResNet (v1b/v1.5) - https://arxiv.org/abs/1512.03385
391
+ * ResNeXt - https://arxiv.org/abs/1611.05431
392
+ * 'Bag of Tricks' / Gluon C, D, E, S variations - https://arxiv.org/abs/1812.01187
393
+ * Weakly-supervised (WSL) Instagram pretrained / ImageNet tuned ResNeXt101 - https://arxiv.org/abs/1805.00932
394
+ * Semi-supervised (SSL) / Semi-weakly Supervised (SWSL) ResNet/ResNeXts - https://arxiv.org/abs/1905.00546
395
+ * ECA-Net (ECAResNet) - https://arxiv.org/abs/1910.03151v4
396
+ * Squeeze-and-Excitation Networks (SEResNet) - https://arxiv.org/abs/1709.01507
397
+ * ResNet-RS - https://arxiv.org/abs/2103.07579
398
+ * Res2Net - https://arxiv.org/abs/1904.01169
399
+ * ResNeSt - https://arxiv.org/abs/2004.08955
400
+ * ReXNet - https://arxiv.org/abs/2007.00992
401
+ * ROPE-ViT - https://arxiv.org/abs/2403.13298
402
+ * SelecSLS - https://arxiv.org/abs/1907.00837
403
+ * Selective Kernel Networks - https://arxiv.org/abs/1903.06586
404
+ * Sequencer2D - https://arxiv.org/abs/2205.01972
405
+ * SHViT - https://arxiv.org/abs/2401.16456
406
+ * SigLIP (image encoder) - https://arxiv.org/abs/2303.15343
407
+ * SigLIP 2 (image encoder) - https://arxiv.org/abs/2502.14786
408
+ * StarNet - https://arxiv.org/abs/2403.19967
409
+ * SwiftFormer - https://arxiv.org/pdf/2303.15446
410
+ * Swin S3 (AutoFormerV2) - https://arxiv.org/abs/2111.14725
411
+ * Swin Transformer - https://arxiv.org/abs/2103.14030
412
+ * Swin Transformer V2 - https://arxiv.org/abs/2111.09883
413
+ * TinyViT - https://arxiv.org/abs/2207.10666
414
+ * Transformer-iN-Transformer (TNT) - https://arxiv.org/abs/2103.00112
415
+ * TResNet - https://arxiv.org/abs/2003.13630
416
+ * Twins (Spatial Attention in Vision Transformers) - https://arxiv.org/pdf/2104.13840.pdf
417
+ * VGG - https://arxiv.org/abs/1409.1556
418
+ * Visformer - https://arxiv.org/abs/2104.12533
419
+ * Vision Transformer - https://arxiv.org/abs/2010.11929
420
+ * ViTamin - https://arxiv.org/abs/2404.02132
421
+ * VOLO (Vision Outlooker) - https://arxiv.org/abs/2106.13112
422
+ * VovNet V2 and V1 - https://arxiv.org/abs/1911.06667
423
+ * Xception - https://arxiv.org/abs/1610.02357
424
+ * Xception (Modified Aligned, Gluon) - https://arxiv.org/abs/1802.02611
425
+ * Xception (Modified Aligned, TF) - https://arxiv.org/abs/1802.02611
426
+ * XCiT (Cross-Covariance Image Transformers) - https://arxiv.org/abs/2106.09681
427
+
428
+ ### Optimizers
429
+ To see full list of optimizers w/ descriptions: `timm.optim.list_optimizers(with_description=True)`
430
+
431
+ Included optimizers available via `timm.optim.create_optimizer_v2` factory method:
432
+ * `adabelief` an implementation of AdaBelief adapted from https://github.com/juntang-zhuang/Adabelief-Optimizer - https://arxiv.org/abs/2010.07468
433
+ * `adafactor` adapted from [FAIRSeq impl](https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py) - https://arxiv.org/abs/1804.04235
434
+ * `adafactorbv` adapted from [Big Vision](https://github.com/google-research/big_vision/blob/main/big_vision/optax.py) - https://arxiv.org/abs/2106.04560
435
+ * `adahessian` by [David Samuel](https://github.com/davda54/ada-hessian) - https://arxiv.org/abs/2006.00719
436
+ * `adamp` and `sgdp` by [Naver ClovAI](https://github.com/clovaai) - https://arxiv.org/abs/2006.08217
437
+ * `adamuon` and `nadamuon` as per https://github.com/Chongjie-Si/AdaMuon - https://arxiv.org/abs/2507.11005
438
+ * `adan` an implementation of Adan adapted from https://github.com/sail-sg/Adan - https://arxiv.org/abs/2208.06677
439
+ * `adopt` ADOPT adapted from https://github.com/iShohei220/adopt - https://arxiv.org/abs/2411.02853
440
+ * `kron` PSGD w/ Kronecker-factored preconditioner from https://github.com/evanatyourservice/kron_torch - https://sites.google.com/site/lixilinx/home/psgd
441
+ * `lamb` an implementation of Lamb and LambC (w/ trust-clipping) cleaned up and modified to support use with XLA - https://arxiv.org/abs/1904.00962
442
+ * `laprop` optimizer from https://github.com/Z-T-WANG/LaProp-Optimizer - https://arxiv.org/abs/2002.04839
443
+ * `lars` an implementation of LARS and LARC (w/ trust-clipping) - https://arxiv.org/abs/1708.03888
444
+ * `lion` and implementation of Lion adapted from https://github.com/google/automl/tree/master/lion - https://arxiv.org/abs/2302.06675
445
+ * `lookahead` adapted from impl by [Liam](https://github.com/alphadl/lookahead.pytorch) - https://arxiv.org/abs/1907.08610
446
+ * `madgrad` an implementation of MADGRAD adapted from https://github.com/facebookresearch/madgrad - https://arxiv.org/abs/2101.11075
447
+ * `mars` MARS optimizer from https://github.com/AGI-Arena/MARS - https://arxiv.org/abs/2411.10438
448
+ * `muon` MUON optimizer from https://github.com/KellerJordan/Muon with numerous additions and improved non-transformer behaviour
449
+ * `nadam` an implementation of Adam w/ Nesterov momentum
450
+ * `nadamw` an implementation of AdamW (Adam w/ decoupled weight-decay) w/ Nesterov momentum. A simplified impl based on https://github.com/mlcommons/algorithmic-efficiency
451
+ * `novograd` by [Masashi Kimura](https://github.com/convergence-lab/novograd) - https://arxiv.org/abs/1905.11286
452
+ * `radam` by [Liyuan Liu](https://github.com/LiyuanLucasLiu/RAdam) - https://arxiv.org/abs/1908.03265
453
+ * `rmsprop_tf` adapted from PyTorch RMSProp by myself. Reproduces much improved Tensorflow RMSProp behaviour
454
+ * `sgdw` and implementation of SGD w/ decoupled weight-decay
455
+ * `fused<name>` optimizers by name with [NVIDIA Apex](https://github.com/NVIDIA/apex/tree/master/apex/optimizers) installed
456
+ * `bnb<name>` optimizers by name with [BitsAndBytes](https://github.com/TimDettmers/bitsandbytes) installed
457
+ * `cadamw`, `clion`, and more 'Cautious' optimizers from https://github.com/kyleliang919/C-Optim - https://arxiv.org/abs/2411.16085
458
+ * `adam`, `adamw`, `rmsprop`, `adadelta`, `adagrad`, and `sgd` pass through to `torch.optim` implementations
459
+ * `c` suffix (eg `adamc`, `nadamc` to implement 'corrected weight decay' in https://arxiv.org/abs/2506.02285)
460
+
461
+ ### Augmentations
462
+ * Random Erasing from [Zhun Zhong](https://github.com/zhunzhong07/Random-Erasing/blob/master/transforms.py) - https://arxiv.org/abs/1708.04896)
463
+ * Mixup - https://arxiv.org/abs/1710.09412
464
+ * CutMix - https://arxiv.org/abs/1905.04899
465
+ * AutoAugment (https://arxiv.org/abs/1805.09501) and RandAugment (https://arxiv.org/abs/1909.13719) ImageNet configurations modeled after impl for EfficientNet training (https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py)
466
+ * AugMix w/ JSD loss, JSD w/ clean + augmented mixing support works with AutoAugment and RandAugment as well - https://arxiv.org/abs/1912.02781
467
+ * SplitBachNorm - allows splitting batch norm layers between clean and augmented (auxiliary batch norm) data
468
+
469
+ ### Regularization
470
+ * DropPath aka "Stochastic Depth" - https://arxiv.org/abs/1603.09382
471
+ * DropBlock - https://arxiv.org/abs/1810.12890
472
+ * Blur Pooling - https://arxiv.org/abs/1904.11486
473
+
474
+ ### Other
475
+
476
+ Several (less common) features that I often utilize in my projects are included. Many of their additions are the reason why I maintain my own set of models, instead of using others' via PIP:
477
+
478
+ * All models have a common default configuration interface and API for
479
+ * accessing/changing the classifier - `get_classifier` and `reset_classifier`
480
+ * doing a forward pass on just the features - `forward_features` (see [documentation](https://huggingface.co/docs/timm/feature_extraction))
481
+ * these makes it easy to write consistent network wrappers that work with any of the models
482
+ * All models support multi-scale feature map extraction (feature pyramids) via create_model (see [documentation](https://huggingface.co/docs/timm/feature_extraction))
483
+ * `create_model(name, features_only=True, out_indices=..., output_stride=...)`
484
+ * `out_indices` creation arg specifies which feature maps to return, these indices are 0 based and generally correspond to the `C(i + 1)` feature level.
485
+ * `output_stride` creation arg controls output stride of the network by using dilated convolutions. Most networks are stride 32 by default. Not all networks support this.
486
+ * feature map channel counts, reduction level (stride) can be queried AFTER model creation via the `.feature_info` member
487
+ * All models have a consistent pretrained weight loader that adapts last linear if necessary, and from 3 to 1 channel input if desired
488
+ * High performance [reference training, validation, and inference scripts](https://huggingface.co/docs/timm/training_script) that work in several process/GPU modes:
489
+ * NVIDIA DDP w/ a single GPU per process, multiple processes with APEX present (AMP mixed-precision optional)
490
+ * PyTorch DistributedDataParallel w/ multi-gpu, single process (AMP disabled as it crashes when enabled)
491
+ * PyTorch w/ single GPU single process (AMP optional)
492
+ * A dynamic global pool implementation that allows selecting from average pooling, max pooling, average + max, or concat([average, max]) at model creation. All global pooling is adaptive average by default and compatible with pretrained weights.
493
+ * A 'Test Time Pool' wrapper that can wrap any of the included models and usually provides improved performance doing inference with input images larger than the training size. Idea adapted from original DPN implementation when I ported (https://github.com/cypw/DPNs)
494
+ * Learning rate schedulers
495
+ * Ideas adopted from
496
+ * [AllenNLP schedulers](https://github.com/allenai/allennlp/tree/master/allennlp/training/learning_rate_schedulers)
497
+ * [FAIRseq lr_scheduler](https://github.com/pytorch/fairseq/tree/master/fairseq/optim/lr_scheduler)
498
+ * SGDR: Stochastic Gradient Descent with Warm Restarts (https://arxiv.org/abs/1608.03983)
499
+ * Schedulers include `step`, `cosine` w/ restarts, `tanh` w/ restarts, `plateau`
500
+ * Space-to-Depth by [mrT23](https://github.com/mrT23/TResNet/blob/master/src/models/tresnet/layers/space_to_depth.py) (https://arxiv.org/abs/1801.04590)
501
+ * Adaptive Gradient Clipping (https://arxiv.org/abs/2102.06171, https://github.com/deepmind/deepmind-research/tree/master/nfnets)
502
+ * An extensive selection of channel and/or spatial attention modules:
503
+ * Bottleneck Transformer - https://arxiv.org/abs/2101.11605
504
+ * CBAM - https://arxiv.org/abs/1807.06521
505
+ * Effective Squeeze-Excitation (ESE) - https://arxiv.org/abs/1911.06667
506
+ * Efficient Channel Attention (ECA) - https://arxiv.org/abs/1910.03151
507
+ * Gather-Excite (GE) - https://arxiv.org/abs/1810.12348
508
+ * Global Context (GC) - https://arxiv.org/abs/1904.11492
509
+ * Halo - https://arxiv.org/abs/2103.12731
510
+ * Involution - https://arxiv.org/abs/2103.06255
511
+ * Lambda Layer - https://arxiv.org/abs/2102.08602
512
+ * Non-Local (NL) - https://arxiv.org/abs/1711.07971
513
+ * Squeeze-and-Excitation (SE) - https://arxiv.org/abs/1709.01507
514
+ * Selective Kernel (SK) - (https://arxiv.org/abs/1903.06586
515
+ * Split (SPLAT) - https://arxiv.org/abs/2004.08955
516
+ * Shifted Window (SWIN) - https://arxiv.org/abs/2103.14030
517
+
518
+ ## Results
519
+
520
+ Model validation results can be found in the [results tables](results/README.md)
521
+
522
+ ## Getting Started (Documentation)
523
+
524
+ The official documentation can be found at https://huggingface.co/docs/hub/timm. Documentation contributions are welcome.
525
+
526
+ [Getting Started with PyTorch Image Models (timm): A Practitioner’s Guide](https://towardsdatascience.com/getting-started-with-pytorch-image-models-timm-a-practitioners-guide-4e77b4bf9055-2/) by [Chris Hughes](https://github.com/Chris-hughes10) is an extensive blog post covering many aspects of `timm` in detail.
527
+
528
+ [timmdocs](http://timm.fast.ai/) is an alternate set of documentation for `timm`. A big thanks to [Aman Arora](https://github.com/amaarora) for his efforts creating timmdocs.
529
+
530
+ [paperswithcode](https://paperswithcode.com/lib/timm) is a good resource for browsing the models within `timm`.
531
+
532
+ ## Train, Validation, Inference Scripts
533
+
534
+ The root folder of the repository contains reference train, validation, and inference scripts that work with the included models and other features of this repository. They are adaptable for other datasets and use cases with a little hacking. See [documentation](https://huggingface.co/docs/timm/training_script).
535
+
536
+ ## Awesome PyTorch Resources
537
+
538
+ One of the greatest assets of PyTorch is the community and their contributions. A few of my favourite resources that pair well with the models and components here are listed below.
539
+
540
+ ### Object Detection, Instance and Semantic Segmentation
541
+ * Detectron2 - https://github.com/facebookresearch/detectron2
542
+ * Segmentation Models (Semantic) - https://github.com/qubvel/segmentation_models.pytorch
543
+ * EfficientDet (Obj Det, Semantic soon) - https://github.com/rwightman/efficientdet-pytorch
544
+
545
+ ### Computer Vision / Image Augmentation
546
+ * Albumentations - https://github.com/albumentations-team/albumentations
547
+ * Kornia - https://github.com/kornia/kornia
548
+
549
+ ### Knowledge Distillation
550
+ * RepDistiller - https://github.com/HobbitLong/RepDistiller
551
+ * torchdistill - https://github.com/yoshitomo-matsubara/torchdistill
552
+
553
+ ### Metric Learning
554
+ * PyTorch Metric Learning - https://github.com/KevinMusgrave/pytorch-metric-learning
555
+
556
+ ### Training / Frameworks
557
+ * fastai - https://github.com/fastai/fastai
558
+ * lightly_train - https://github.com/lightly-ai/lightly-train
559
+
560
+ ### Deployment
561
+ * timmx (Export timm models to ONNX, CoreML, LiteRT, TensorRT, and more) - https://github.com/Boulaouaney/timmx
562
+
563
+ ## Licenses
564
+
565
+ ### Code
566
+ The code here is licensed Apache 2.0. I've taken care to make sure any third party code included or adapted has compatible (permissive) licenses such as MIT, BSD, etc. I've made an effort to avoid any GPL / LGPL conflicts. That said, it is your responsibility to ensure you comply with licenses here and conditions of any dependent licenses. Where applicable, I've linked the sources/references for various components in docstrings. If you think I've missed anything please create an issue.
567
+
568
+ ### Pretrained Weights
569
+ So far all of the pretrained weights available here are pretrained on ImageNet with a select few that have some additional pretraining (see extra note below). ImageNet was released for non-commercial research purposes only (https://image-net.org/download). It's not clear what the implications of that are for the use of pretrained weights from that dataset. Any models I have trained with ImageNet are done for research purposes and one should assume that the original dataset license applies to the weights. It's best to seek legal advice if you intend to use the pretrained weights in a commercial product.
570
+
571
+ #### Pretrained on more than ImageNet
572
+ Several weights included or references here were pretrained with proprietary datasets that I do not have access to. These include the Facebook WSL, SSL, SWSL ResNe(Xt) and the Google Noisy Student EfficientNet models. The Facebook models have an explicit non-commercial license (CC-BY-NC 4.0, https://github.com/facebookresearch/semi-supervised-ImageNet1K-models, https://github.com/facebookresearch/WSL-Images). The Google models do not appear to have any restriction beyond the Apache 2.0 license (and ImageNet concerns). In either case, you should contact Facebook or Google with any questions.
573
+
574
+ ## Citing
575
+
576
+ ### BibTeX
577
+
578
+ ```bibtex
579
+ @misc{rw2019timm,
580
+ author = {Ross Wightman},
581
+ title = {PyTorch Image Models},
582
+ year = {2019},
583
+ publisher = {GitHub},
584
+ journal = {GitHub repository},
585
+ doi = {10.5281/zenodo.4414861},
586
+ howpublished = {\url{https://github.com/rwightman/pytorch-image-models}}
587
+ }
588
+ ```
589
+
590
+ ### Latest DOI
591
+
592
+ [![DOI](https://zenodo.org/badge/168799526.svg)](https://zenodo.org/badge/latestdoi/168799526)
.cache/pip/http-v2/7/f/f/b/a/7ffbaade46b578649cfc115650c307df3346f8f8e3d20f832aa9ec7b ADDED
Binary file (1.2 kB). View file
 
.cache/pip/http-v2/8/1/8/8/f/8188f9db6169e57bb653240cc02c629488d0d899420b0725db0f7e4a ADDED
Binary file (1.17 kB). View file
 
.cache/pip/http-v2/8/a/c/4/d/8ac4d14dc45e27d21da49fb515570b6f875b78707de9b08ce1088d1b ADDED
Binary file (1.9 kB). View file
 
.cache/pip/http-v2/8/a/c/4/d/8ac4d14dc45e27d21da49fb515570b6f875b78707de9b08ce1088d1b.body ADDED
Binary file (17.3 kB). View file
 
.cache/pip/http-v2/8/e/c/0/1/8ec01c6c0d8da8090ee14b669ee42a1879d3dc488903f676b506ef69 ADDED
Binary file (1.24 kB). View file
 
.cache/pip/http-v2/8/e/c/0/1/8ec01c6c0d8da8090ee14b669ee42a1879d3dc488903f676b506ef69.body ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: hf-xet
3
+ Version: 1.5.2
4
+ Classifier: Development Status :: 5 - Production/Stable
5
+ Classifier: License :: OSI Approved :: Apache Software License
6
+ Classifier: Programming Language :: Rust
7
+ Classifier: Programming Language :: Python :: Implementation :: CPython
8
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Programming Language :: Python :: 3.8
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: Free Threading
19
+ Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Requires-Dist: pytest ; extra == 'tests'
22
+ Provides-Extra: tests
23
+ License-File: LICENSE
24
+ Summary: Fast transfer of large files with the Hugging Face Hub.
25
+ Maintainer-email: Rajat Arya <rajat@rajatarya.com>, Jared Sulzdorf <j.sulzdorf@gmail.com>, Di Xiao <di@huggingface.co>, Assaf Vayner <assaf@huggingface.co>, Hoyt Koepke <hoytak@gmail.com>
26
+ License-Expression: Apache-2.0
27
+ Requires-Python: >=3.8
28
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
29
+ Project-URL: Documentation, https://huggingface.co/docs/hub/xet/index
30
+ Project-URL: Homepage, https://github.com/huggingface/xet-core
31
+ Project-URL: Issues, https://github.com/huggingface/xet-core/issues
32
+ Project-URL: Repository, https://github.com/huggingface/xet-core.git
33
+
34
+ <!---
35
+ Copyright 2024 The HuggingFace Team. All rights reserved.
36
+
37
+ Licensed under the Apache License, Version 2.0 (the "License");
38
+ you may not use this file except in compliance with the License.
39
+ You may obtain a copy of the License at
40
+
41
+ http://www.apache.org/licenses/LICENSE-2.0
42
+
43
+ Unless required by applicable law or agreed to in writing, software
44
+ distributed under the License is distributed on an "AS IS" BASIS,
45
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
46
+ See the License for the specific language governing permissions and
47
+ limitations under the License.
48
+ -->
49
+ <p align="center">
50
+ <a href="https://github.com/huggingface/xet-core/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/huggingface/xet-core.svg?color=blue"></a>
51
+ <a href="https://github.com/huggingface/xet-core/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/xet-core.svg"></a>
52
+ <a href="https://github.com/huggingface/xet-core/blob/main/CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg"></a>
53
+ </p>
54
+
55
+ <h3 align="center">
56
+ <p>🤗 hf-xet - xet client tech, used in <a target="_blank" href="https://github.com/huggingface/huggingface_hub/">huggingface_hub</a></p>
57
+ </h3>
58
+
59
+ ## Welcome
60
+
61
+ `hf-xet` enables `huggingface_hub` to utilize xet storage for uploading and downloading to HF Hub. Xet storage provides chunk-based deduplication, efficient storage/retrieval with local disk caching, and backwards compatibility with Git LFS. This library is not meant to be used directly, and is instead intended to be used from [huggingface_hub](https://pypi.org/project/huggingface-hub).
62
+
63
+ ## Key features
64
+
65
+ ♻ **chunk-based deduplication implementation**: avoid transferring and storing chunks that are shared across binary files (models, datasets, etc).
66
+
67
+ 🤗 **Python bindings**: bindings for [huggingface_hub](https://github.com/huggingface/huggingface_hub/) package.
68
+
69
+ ↔ **network communications**: concurrent communication to HF Hub Xet backend services (CAS).
70
+
71
+ 🔖 **local disk caching**: chunk-based cache that sits alongside the existing [huggingface_hub disk cache](https://huggingface.co/docs/huggingface_hub/guides/manage-cache).
72
+
73
+ ## Installation
74
+
75
+ Install the `hf_xet` package with [pip](https://pypi.org/project/hf-xet/):
76
+
77
+ ```bash
78
+ pip install hf_xet
79
+ ```
80
+
81
+ ## Quick Start
82
+
83
+ `hf_xet` is not intended to be run independently as it is expected to be used from `huggingface_hub`, so to get started with `huggingface_hub` check out the documentation [here]("https://hf.co/docs/huggingface_hub").
84
+
85
+ ## Contributions (feature requests, bugs, etc.) are encouraged & appreciated 💙💚💛💜🧡❤️
86
+
87
+ Please join us in making hf-xet better. We value everyone's contributions. Code is not the only way to help. Answering questions, helping each other, improving documentation, filing issues all help immensely. If you are interested in contributing (please do!), check out the [contribution guide](https://github.com/huggingface/xet-core/blob/main/CONTRIBUTING.md) for this repository.
.cache/pip/http-v2/8/f/0/a/d/8f0ad583652318494c12da41e4d30ff6225ec73d448a0754a0a7e898 ADDED
Binary file (1.9 kB). View file
 
.cache/pip/http-v2/b/1/f/5/d/b1f5dc01896eee598e8915be35e61304ad2b16363d00711f8576642c ADDED
Binary file (1.9 kB). View file
 
.cache/pip/http-v2/b/9/9/a/d/b99ad330dfd2e9e0337861ace33d07fca2ddfd480ba4473963ebc23d ADDED
Binary file (1.2 kB). View file
 
.cache/pip/http-v2/f/1/9/c/b/f19cb9f2548ebec3162f98dc0753cc5fe07d32364a02b1720f376edb ADDED
Binary file (1.9 kB). View file
 
.cache/pip/http-v2/f/1/9/c/b/f19cb9f2548ebec3162f98dc0753cc5fe07d32364a02b1720f376edb.body ADDED
Binary file (26.5 kB). View file
 
.cache/pip/http-v2/f/6/4/9/7/f64975d28276977ea56e4922737def644a797957c860c54f5b5bc122 ADDED
Binary file (1.25 kB). View file
 
.cache/pip/http-v2/f/6/4/9/7/f64975d28276977ea56e4922737def644a797957c860c54f5b5bc122.body ADDED
The diff for this file is too large to render. See raw diff
 
.cache/pip/http-v2/f/c/6/8/7/fc687abc6120c7bc7cfd867fe3788604e9f8e9dcf17e51396d803e25 ADDED
Binary file (1.17 kB). View file
 
.cache/pip/http-v2/f/c/7/7/6/fc776fd0a9dd67f0a511e4cdeb9638db3cb4cdd09d04b821c1ec4c93 ADDED
Binary file (1.19 kB). View file
 
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_backends/__init__.py ADDED
File without changes
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_backends/_asyncio.py ADDED
The diff for this file is too large to render. See raw diff
 
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/_core/__init__.py ADDED
File without changes
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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
+ """
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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)
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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
+ """
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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)
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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()
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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)
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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))
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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
+ )
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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
+ )
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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)
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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()
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/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()
.cache/uv/archive-v0/1F1AEJJoVrj01vzTyD0QR/anyio/abc/__init__.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from ._eventloop import AsyncBackend as AsyncBackend
4
+ from ._resources import AsyncResource as AsyncResource
5
+ from ._sockets import ConnectedUDPSocket as ConnectedUDPSocket
6
+ from ._sockets import ConnectedUNIXDatagramSocket as ConnectedUNIXDatagramSocket
7
+ from ._sockets import IPAddressType as IPAddressType
8
+ from ._sockets import IPSockAddrType as IPSockAddrType
9
+ from ._sockets import SocketAttribute as SocketAttribute
10
+ from ._sockets import SocketListener as SocketListener
11
+ from ._sockets import SocketStream as SocketStream
12
+ from ._sockets import UDPPacketType as UDPPacketType
13
+ from ._sockets import UDPSocket as UDPSocket
14
+ from ._sockets import UNIXDatagramPacketType as UNIXDatagramPacketType
15
+ from ._sockets import UNIXDatagramSocket as UNIXDatagramSocket
16
+ from ._sockets import UNIXSocketStream as UNIXSocketStream
17
+ from ._streams import AnyByteReceiveStream as AnyByteReceiveStream
18
+ from ._streams import AnyByteSendStream as AnyByteSendStream
19
+ from ._streams import AnyByteStream as AnyByteStream
20
+ from ._streams import AnyByteStreamConnectable as AnyByteStreamConnectable
21
+ from ._streams import AnyUnreliableByteReceiveStream as AnyUnreliableByteReceiveStream
22
+ from ._streams import AnyUnreliableByteSendStream as AnyUnreliableByteSendStream
23
+ from ._streams import AnyUnreliableByteStream as AnyUnreliableByteStream
24
+ from ._streams import ByteReceiveStream as ByteReceiveStream
25
+ from ._streams import ByteSendStream as ByteSendStream
26
+ from ._streams import ByteStream as ByteStream
27
+ from ._streams import ByteStreamConnectable as ByteStreamConnectable
28
+ from ._streams import Listener as Listener
29
+ from ._streams import ObjectReceiveStream as ObjectReceiveStream
30
+ from ._streams import ObjectSendStream as ObjectSendStream
31
+ from ._streams import ObjectStream as ObjectStream
32
+ from ._streams import ObjectStreamConnectable as ObjectStreamConnectable
33
+ from ._streams import UnreliableObjectReceiveStream as UnreliableObjectReceiveStream
34
+ from ._streams import UnreliableObjectSendStream as UnreliableObjectSendStream
35
+ from ._streams import UnreliableObjectStream as UnreliableObjectStream
36
+ from ._subprocesses import Process as Process
37
+ from ._tasks import TaskGroup as TaskGroup
38
+ from ._tasks import TaskStatus as TaskStatus
39
+ from ._testing import TestRunner as TestRunner
40
+
41
+ # Re-exported here, for backwards compatibility
42
+ # isort: off
43
+ from .._core._synchronization import (
44
+ CapacityLimiter as CapacityLimiter,
45
+ Condition as Condition,
46
+ Event as Event,
47
+ Lock as Lock,
48
+ Semaphore as Semaphore,
49
+ )
50
+ from .._core._tasks import CancelScope as CancelScope
51
+ from ..from_thread import BlockingPortal as BlockingPortal
52
+
53
+ # Re-export imports so they look like they live directly in this package
54
+ for __value in list(locals().values()):
55
+ if getattr(__value, "__module__", "").startswith("anyio.abc."):
56
+ __value.__module__ = __name__
57
+
58
+ del __value