pytrove 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. pytrove-1.0.0/LICENSE +21 -0
  2. pytrove-1.0.0/PKG-INFO +203 -0
  3. pytrove-1.0.0/README.md +147 -0
  4. pytrove-1.0.0/pyproject.toml +75 -0
  5. pytrove-1.0.0/pytrove/__init__.py +39 -0
  6. pytrove-1.0.0/pytrove/__meta__.py +1 -0
  7. pytrove-1.0.0/pytrove/_async_tools.py +202 -0
  8. pytrove-1.0.0/pytrove/_devices.py +758 -0
  9. pytrove-1.0.0/pytrove/_optional.py +107 -0
  10. pytrove-1.0.0/pytrove/_typings_py312.py +44 -0
  11. pytrove-1.0.0/pytrove/async_tools.py +433 -0
  12. pytrove-1.0.0/pytrove/callable_tools.py +360 -0
  13. pytrove-1.0.0/pytrove/classes.py +1288 -0
  14. pytrove-1.0.0/pytrove/country_tools.py +70 -0
  15. pytrove-1.0.0/pytrove/crypto_tools.py +143 -0
  16. pytrove-1.0.0/pytrove/data/tg_points.json +214 -0
  17. pytrove-1.0.0/pytrove/data_tools.py +160 -0
  18. pytrove-1.0.0/pytrove/date_tools.py +168 -0
  19. pytrove-1.0.0/pytrove/email_tools.py +124 -0
  20. pytrove-1.0.0/pytrove/enums.py +78 -0
  21. pytrove-1.0.0/pytrove/errors.py +13 -0
  22. pytrove-1.0.0/pytrove/files_tools.py +97 -0
  23. pytrove-1.0.0/pytrove/iter_tools.py +102 -0
  24. pytrove-1.0.0/pytrove/logging_tools.py +120 -0
  25. pytrove-1.0.0/pytrove/misc_tools.py +205 -0
  26. pytrove-1.0.0/pytrove/models/__init__.py +16 -0
  27. pytrove-1.0.0/pytrove/models/base.py +218 -0
  28. pytrove-1.0.0/pytrove/models/logging_models.py +61 -0
  29. pytrove-1.0.0/pytrove/models/misc_models.py +265 -0
  30. pytrove-1.0.0/pytrove/num_tools.py +129 -0
  31. pytrove-1.0.0/pytrove/phone_tools.py +120 -0
  32. pytrove-1.0.0/pytrove/py.typed +0 -0
  33. pytrove-1.0.0/pytrove/text_tools.py +373 -0
  34. pytrove-1.0.0/pytrove/tg_tools.py +309 -0
  35. pytrove-1.0.0/pytrove/typings.py +121 -0
  36. pytrove-1.0.0/pytrove/validate_tools.py +428 -0
  37. pytrove-1.0.0/tests/test_async_tools.py +66 -0
  38. pytrove-1.0.0/tests/test_base_dataclass.py +111 -0
  39. pytrove-1.0.0/tests/test_callable_and_misc_tools.py +114 -0
  40. pytrove-1.0.0/tests/test_crypto_tools.py +53 -0
  41. pytrove-1.0.0/tests/test_date_tools.py +59 -0
  42. pytrove-1.0.0/tests/test_files_tools.py +71 -0
  43. pytrove-1.0.0/tests/test_iter_tools.py +37 -0
  44. pytrove-1.0.0/tests/test_num_and_text_tools.py +67 -0
  45. pytrove-1.0.0/tests/test_text_tools.py +88 -0
  46. pytrove-1.0.0/tests/test_typings_and_validate.py +102 -0
pytrove-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abdullah (github.com/eeeob)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
pytrove-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,203 @@
1
+ Metadata-Version: 2.5
2
+ Name: pytrove
3
+ Version: 1.0.0
4
+ Summary: Python Tools library for some services
5
+ Project-URL: Homepage, https://github.com/eeeob/pytrove
6
+ Author-email: Abdullah <aldheeb01@gmail.com>
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: typing-extensions>=4.0; python_version < '3.13'
21
+ Provides-Extra: bs4
22
+ Requires-Dist: beautifulsoup4>=4.14.3; extra == 'bs4'
23
+ Provides-Extra: country
24
+ Requires-Dist: phonenumbers>=9.0.21; extra == 'country'
25
+ Requires-Dist: pycountry>=26.2.16; extra == 'country'
26
+ Provides-Extra: crypto
27
+ Requires-Dist: cryptography>=48.0.1; extra == 'crypto'
28
+ Provides-Extra: dev
29
+ Requires-Dist: hatch<=1.16.5; extra == 'dev'
30
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
31
+ Requires-Dist: pytest>=8; extra == 'dev'
32
+ Requires-Dist: twine<=6.2.0; extra == 'dev'
33
+ Provides-Extra: full
34
+ Requires-Dist: aioimaplib>=2.0.1; extra == 'full'
35
+ Requires-Dist: beautifulsoup4>=4.14.3; extra == 'full'
36
+ Requires-Dist: cryptography>=48.0.1; extra == 'full'
37
+ Requires-Dist: kurigram>=2.1.35; extra == 'full'
38
+ Requires-Dist: phonenumbers>=9.0.21; extra == 'full'
39
+ Requires-Dist: pycountry>=26.2.16; extra == 'full'
40
+ Requires-Dist: pymongo>=4.6.3; extra == 'full'
41
+ Requires-Dist: typeguard>=4.3; extra == 'full'
42
+ Requires-Dist: wrapt>=1.16; extra == 'full'
43
+ Provides-Extra: imap
44
+ Requires-Dist: aioimaplib>=2.0.1; extra == 'imap'
45
+ Provides-Extra: mongo
46
+ Requires-Dist: pymongo>=4.6.3; extra == 'mongo'
47
+ Provides-Extra: phone
48
+ Requires-Dist: phonenumbers>=9.0.21; extra == 'phone'
49
+ Provides-Extra: proxy
50
+ Requires-Dist: wrapt>=1.16; extra == 'proxy'
51
+ Provides-Extra: tg
52
+ Requires-Dist: kurigram>=2.1.35; extra == 'tg'
53
+ Provides-Extra: typecheck
54
+ Requires-Dist: typeguard>=4.3; extra == 'typecheck'
55
+ Description-Content-Type: text/markdown
56
+
57
+ # pytrove 🛠️
58
+
59
+ [![PyPI version](https://img.shields.io/pypi/v/pytrove)](https://pypi.org/project/pytrove/)
60
+ [![Python versions](https://img.shields.io/pypi/pyversions/pytrove)](https://pypi.org/project/pytrove/)
61
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
62
+
63
+ **pytrove** is a modern Python utilities library providing async-ready helpers for backend systems, databases, cryptography, and Telegram automation.
64
+
65
+ ---
66
+
67
+ ## ✨ Features
68
+
69
+ * ⚡ **Async-first design** built for modern `asyncio` applications
70
+ * 🗄️ **MongoDB utilities** for cleaner and safer database operations
71
+ * 🔐 **Cryptography helpers** (AES-GCM, secure key derivation)
72
+ * 🤖 **Telegram utilities** using Kurigram integration
73
+ * 📧 **IMAP email utilities** for fetching and parsing emails
74
+ * 🌍 **Country & phone utilities** for region and number handling
75
+ * 🧰 **General utilities** for parsing, validation, and data handling
76
+ * 🧩 **Fully typed codebase** with strict type hints support
77
+
78
+ ---
79
+
80
+ ## 📦 Installation
81
+
82
+ Starting from `v0.2.0`, the library uses **optional dependencies** — install only what you need.
83
+
84
+ ### Minimal install (no optional dependencies)
85
+
86
+ ```bash
87
+ pip install pytrove
88
+ ```
89
+
90
+ ### Install specific features
91
+
92
+ | Extra | Installs | Use for |
93
+ |-------|----------|---------|
94
+ | `crypto` | `cryptography` | Encryption & key derivation |
95
+ | `mongo` | `pymongo` | MongoDB utilities |
96
+ | `phone` | `phonenumbers` | Phone number parsing |
97
+ | `country` | `pycountry`, `phonenumbers` | Country info & region codes |
98
+ | `tg` | `kurigram` | Telegram automation |
99
+ | `imap` | `aioimaplib` | IMAP email fetching |
100
+ | `bs4` | `beautifulsoup4` | HTML email parsing |
101
+ | `typecheck` | `typeguard` | Runtime type validation (`validate_type`) |
102
+ | `proxy` | `wrapt` | Restricted object proxies (`RestrictedProxy`, `WeakRestrictedProxy`, `AioThreadWorker.get_loop`) |
103
+ | `full` | everything above | All features |
104
+
105
+ ```bash
106
+ # Single feature
107
+ pip install "pytrove[crypto]"
108
+
109
+ # Multiple features
110
+ pip install "pytrove[crypto, mongo, phone]"
111
+
112
+ # Everything
113
+ pip install "pytrove[full]"
114
+ ```
115
+
116
+ > **Note:** If you try to use a feature without its required packages installed, you'll get a clear `ImportError` with the exact install command needed.
117
+
118
+ ### Install the latest version from GitHub
119
+
120
+ To install directly from the `main` branch (ahead of the latest PyPI release):
121
+
122
+ ```bash
123
+ pip install git+https://github.com/eeeob/pytrove.git --force-reinstall
124
+ ```
125
+
126
+ ---
127
+
128
+ ## 🚀 Quick Start
129
+
130
+ ### 🔐 Encryption example
131
+
132
+ ```bash
133
+ pip install "pytrove[crypto]"
134
+ ```
135
+
136
+ ```python
137
+ from pytrove import encrypt, decrypt
138
+
139
+ key = "my-secure-key"
140
+
141
+ encrypted = encrypt("secret data", key)
142
+ print(encrypted)
143
+
144
+ decrypted = decrypt(encrypted, key)
145
+ print(decrypted)
146
+ ```
147
+
148
+ ### 🗄️ MongoDB example
149
+
150
+ ```bash
151
+ pip install "pytrove[mongo]"
152
+ ```
153
+
154
+ ```python
155
+ from pytrove import MongoIndex
156
+
157
+ index = MongoIndex.from_dict({"key": {"field": 1}})
158
+ ```
159
+
160
+ ### 🤖 Telegram example
161
+
162
+ ```bash
163
+ pip install "pytrove[tg]"
164
+ ```
165
+
166
+ ```python
167
+ from pytrove import format_tg_username, mention_tg_user
168
+
169
+ username = format_tg_username("@myuser")
170
+ mention = mention_tg_user(123456789, "John")
171
+ ```
172
+
173
+ ---
174
+
175
+ ## 🧪 Development Setup
176
+
177
+ ```bash
178
+ git clone https://github.com/eeeob/pytrove.git
179
+ cd pytrove
180
+ pip install -e ".[full,dev]"
181
+ ```
182
+
183
+ ### Running tests
184
+
185
+ ```bash
186
+ pytest
187
+ ```
188
+
189
+ Tests run in CI across every Python version listed in the classifiers above (3.10 through 3.14), both with the minimal (no-extras) install and with `[full,dev]`.
190
+
191
+ ---
192
+
193
+ ## 📄 License
194
+
195
+ This project is licensed under the **MIT License**.
196
+ See the [LICENSE](LICENSE) file for details.
197
+
198
+ ---
199
+
200
+ ## 📬 Contact
201
+
202
+ * Email: [aldheeb01@gmail.com](mailto:aldheeb01@gmail.com)
203
+ * GitHub: https://github.com/eeeob/pytrove
@@ -0,0 +1,147 @@
1
+ # pytrove 🛠️
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/pytrove)](https://pypi.org/project/pytrove/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/pytrove)](https://pypi.org/project/pytrove/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
6
+
7
+ **pytrove** is a modern Python utilities library providing async-ready helpers for backend systems, databases, cryptography, and Telegram automation.
8
+
9
+ ---
10
+
11
+ ## ✨ Features
12
+
13
+ * ⚡ **Async-first design** built for modern `asyncio` applications
14
+ * 🗄️ **MongoDB utilities** for cleaner and safer database operations
15
+ * 🔐 **Cryptography helpers** (AES-GCM, secure key derivation)
16
+ * 🤖 **Telegram utilities** using Kurigram integration
17
+ * 📧 **IMAP email utilities** for fetching and parsing emails
18
+ * 🌍 **Country & phone utilities** for region and number handling
19
+ * 🧰 **General utilities** for parsing, validation, and data handling
20
+ * 🧩 **Fully typed codebase** with strict type hints support
21
+
22
+ ---
23
+
24
+ ## 📦 Installation
25
+
26
+ Starting from `v0.2.0`, the library uses **optional dependencies** — install only what you need.
27
+
28
+ ### Minimal install (no optional dependencies)
29
+
30
+ ```bash
31
+ pip install pytrove
32
+ ```
33
+
34
+ ### Install specific features
35
+
36
+ | Extra | Installs | Use for |
37
+ |-------|----------|---------|
38
+ | `crypto` | `cryptography` | Encryption & key derivation |
39
+ | `mongo` | `pymongo` | MongoDB utilities |
40
+ | `phone` | `phonenumbers` | Phone number parsing |
41
+ | `country` | `pycountry`, `phonenumbers` | Country info & region codes |
42
+ | `tg` | `kurigram` | Telegram automation |
43
+ | `imap` | `aioimaplib` | IMAP email fetching |
44
+ | `bs4` | `beautifulsoup4` | HTML email parsing |
45
+ | `typecheck` | `typeguard` | Runtime type validation (`validate_type`) |
46
+ | `proxy` | `wrapt` | Restricted object proxies (`RestrictedProxy`, `WeakRestrictedProxy`, `AioThreadWorker.get_loop`) |
47
+ | `full` | everything above | All features |
48
+
49
+ ```bash
50
+ # Single feature
51
+ pip install "pytrove[crypto]"
52
+
53
+ # Multiple features
54
+ pip install "pytrove[crypto, mongo, phone]"
55
+
56
+ # Everything
57
+ pip install "pytrove[full]"
58
+ ```
59
+
60
+ > **Note:** If you try to use a feature without its required packages installed, you'll get a clear `ImportError` with the exact install command needed.
61
+
62
+ ### Install the latest version from GitHub
63
+
64
+ To install directly from the `main` branch (ahead of the latest PyPI release):
65
+
66
+ ```bash
67
+ pip install git+https://github.com/eeeob/pytrove.git --force-reinstall
68
+ ```
69
+
70
+ ---
71
+
72
+ ## 🚀 Quick Start
73
+
74
+ ### 🔐 Encryption example
75
+
76
+ ```bash
77
+ pip install "pytrove[crypto]"
78
+ ```
79
+
80
+ ```python
81
+ from pytrove import encrypt, decrypt
82
+
83
+ key = "my-secure-key"
84
+
85
+ encrypted = encrypt("secret data", key)
86
+ print(encrypted)
87
+
88
+ decrypted = decrypt(encrypted, key)
89
+ print(decrypted)
90
+ ```
91
+
92
+ ### 🗄️ MongoDB example
93
+
94
+ ```bash
95
+ pip install "pytrove[mongo]"
96
+ ```
97
+
98
+ ```python
99
+ from pytrove import MongoIndex
100
+
101
+ index = MongoIndex.from_dict({"key": {"field": 1}})
102
+ ```
103
+
104
+ ### 🤖 Telegram example
105
+
106
+ ```bash
107
+ pip install "pytrove[tg]"
108
+ ```
109
+
110
+ ```python
111
+ from pytrove import format_tg_username, mention_tg_user
112
+
113
+ username = format_tg_username("@myuser")
114
+ mention = mention_tg_user(123456789, "John")
115
+ ```
116
+
117
+ ---
118
+
119
+ ## 🧪 Development Setup
120
+
121
+ ```bash
122
+ git clone https://github.com/eeeob/pytrove.git
123
+ cd pytrove
124
+ pip install -e ".[full,dev]"
125
+ ```
126
+
127
+ ### Running tests
128
+
129
+ ```bash
130
+ pytest
131
+ ```
132
+
133
+ Tests run in CI across every Python version listed in the classifiers above (3.10 through 3.14), both with the minimal (no-extras) install and with `[full,dev]`.
134
+
135
+ ---
136
+
137
+ ## 📄 License
138
+
139
+ This project is licensed under the **MIT License**.
140
+ See the [LICENSE](LICENSE) file for details.
141
+
142
+ ---
143
+
144
+ ## 📬 Contact
145
+
146
+ * Email: [aldheeb01@gmail.com](mailto:aldheeb01@gmail.com)
147
+ * GitHub: https://github.com/eeeob/pytrove
@@ -0,0 +1,75 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+
6
+ [project]
7
+ name = "pytrove"
8
+ dynamic = ["version"]
9
+ description = "Python Tools library for some services"
10
+ requires-python = ">=3.10"
11
+ authors = [{ name = "Abdullah", email = "aldheeb01@gmail.com" }]
12
+ readme = "README.md"
13
+
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.10",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Operating System :: OS Independent",
22
+ "Development Status :: 5 - Production/Stable",
23
+ "Intended Audience :: Developers",
24
+ "Topic :: Software Development :: Libraries :: Python Modules",
25
+ "Typing :: Typed",
26
+ ]
27
+
28
+ dependencies = [
29
+ "typing_extensions>=4.0; python_version<'3.13'",
30
+ ]
31
+
32
+
33
+ [project.urls]
34
+ "Homepage" = "https://github.com/eeeob/pytrove"
35
+
36
+ [project.optional-dependencies]
37
+ dev = [
38
+ "hatch<=1.16.5",
39
+ "twine<=6.2.0",
40
+ "pytest>=8",
41
+ "pytest-asyncio>=0.24",
42
+ ]
43
+
44
+
45
+ mongo = ["pymongo>=4.6.3"]
46
+ country = ["pycountry>=26.2.16", "phonenumbers>=9.0.21"]
47
+ crypto = ["cryptography>=48.0.1"]
48
+ bs4 = ["beautifulsoup4>=4.14.3"]
49
+ imap = ["aioimaplib>=2.0.1"]
50
+ phone = ["phonenumbers>=9.0.21"]
51
+ tg = ["kurigram>=2.1.35"]
52
+ typecheck = ["typeguard>=4.3"]
53
+ proxy = ["wrapt>=1.16"]
54
+
55
+ full = [
56
+ "pytrove[imap,phone,country,bs4,mongo,tg,crypto,typecheck,proxy]"
57
+ ]
58
+
59
+ [tool.hatch.build.targets.sdist]
60
+ exclude = [".github/",]
61
+
62
+ [tool.hatch.version]
63
+ path = "pytrove/__meta__.py"
64
+
65
+
66
+ [tool.hatch.metadata]
67
+ allow-direct-references = true
68
+
69
+ [tool.hatch.build.targets.wheel]
70
+ ignore-vcs = true
71
+ packages = ["pytrove"]
72
+
73
+ [tool.pytest.ini_options]
74
+ testpaths = ["tests"]
75
+ asyncio_mode = "auto"
@@ -0,0 +1,39 @@
1
+ from .__meta__ import __version__
2
+
3
+ from .validate_tools import *
4
+ from .date_tools import *
5
+ from .num_tools import *
6
+ from .files_tools import *
7
+ from .iter_tools import *
8
+ from .text_tools import *
9
+ from .async_tools import *
10
+ from .misc_tools import *
11
+ from .tg_tools import *
12
+ from .phone_tools import *
13
+ from .country_tools import *
14
+ from .crypto_tools import *
15
+ from .data_tools import *
16
+ from .callable_tools import *
17
+ from .logging_tools import *
18
+ from .email_tools import *
19
+ from .classes import *
20
+
21
+ __all__ = (
22
+ *validate_tools.__all__,
23
+ *date_tools.__all__,
24
+ *num_tools.__all__,
25
+ *files_tools.__all__,
26
+ *iter_tools.__all__,
27
+ *text_tools.__all__,
28
+ *async_tools.__all__,
29
+ *misc_tools.__all__,
30
+ *tg_tools.__all__,
31
+ *phone_tools.__all__,
32
+ *country_tools.__all__,
33
+ *crypto_tools.__all__,
34
+ *data_tools.__all__,
35
+ *callable_tools.__all__,
36
+ *classes.__all__,
37
+ *logging_tools.__all__,
38
+ *email_tools.__all__,
39
+ )
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
@@ -0,0 +1,202 @@
1
+ import asyncio
2
+ import sys
3
+
4
+ from typing import Any, Awaitable, List, Optional, Union, TYPE_CHECKING, overload
5
+ from .typings import _T, _True, _False
6
+
7
+
8
+ _PY314 = sys.version_info >= (3, 14)
9
+
10
+ def _get_fut_loop(fut):
11
+ try:
12
+ get_loop = fut.get_loop
13
+ except AttributeError:
14
+ pass
15
+ else:
16
+ return get_loop()
17
+ return fut._loop
18
+
19
+ def _get_running_loop() -> Optional[asyncio.AbstractEventLoop]:
20
+ try:
21
+ return asyncio.get_running_loop()
22
+ except RuntimeError:
23
+ return
24
+
25
+
26
+ class _GatheringFuture(asyncio.Future):
27
+ def __init__(self, children, *, loop):
28
+ super().__init__(loop=loop)
29
+
30
+ self._children = children
31
+
32
+ if not TYPE_CHECKING:
33
+ @property
34
+ def cancel_message(self) -> Optional[Any]:
35
+ return getattr(self, "_cancel_message", None)
36
+
37
+ @cancel_message.setter
38
+ def cancel_message(self, value: Optional[Any]):
39
+ setattr(self, "_cancel_message", value)
40
+
41
+
42
+ def cancel(self, msg: Optional[Any] = None) -> bool:
43
+ # Cancelling the outer future does not cancel *this* future
44
+ # immediately -- it forwards the request to every child and lets
45
+ # them unwind first, exactly like asyncio.gather(). _done_callback
46
+ # only turns `outer` itself into a CancelledError once every child
47
+ # has actually finished (npending == 0); until then `outer` stays
48
+ # pending even though a cancellation is already in flight.
49
+ if self.done():
50
+ return False
51
+
52
+ ret = False
53
+
54
+ for child in self._children:
55
+ if child.cancel(msg=msg):
56
+ ret = True
57
+
58
+ if ret:
59
+ self.cancel_message = "" if msg is None else msg
60
+
61
+ return ret
62
+
63
+
64
+ @overload
65
+ def _gather_cancel_on_error(*awaitables: Awaitable[_T], return_exceptions: _False = False) -> asyncio.Future[List[_T]]:...
66
+ @overload
67
+ def _gather_cancel_on_error(*awaitables: Awaitable[_T], return_exceptions: _True) -> asyncio.Future[List[Union[_T, Exception]]]:...
68
+ def _gather_cancel_on_error(*awaitables, return_exceptions = False):
69
+ """Reimplementation of asyncio.gather() that cancels every sibling as soon
70
+ as one fails (asyncio.gather() itself leaves the rest running).
71
+
72
+ `_done_callback` fires once per child future and does one of three things:
73
+ - if `outer` is already resolved (a prior sibling failed first, or the
74
+ caller cancelled `outer` itself -- see _GatheringFuture.cancel above),
75
+ the result/exception is only drained via fut.exception() so asyncio's
76
+ "exception was never retrieved" warning doesn't fire on a future
77
+ nobody will ever await again;
78
+ - if this child failed and `return_exceptions` is False, `outer` is
79
+ failed with that exception and every other still-running child is
80
+ cancelled -- this is the actual "cancel on error" behavior;
81
+ - once every child has reported in (`npending == 0`), results are
82
+ collected in the original awaitables order and `outer` is resolved --
83
+ as a success, or as CancelledError if `outer` was cancelled while
84
+ children were still finishing (see _GatheringFuture.cancel, which
85
+ lets already-running children finish instead of force-stopping them).
86
+
87
+ `awaitable_2_fut` deduplicates: passing the same awaitable twice must not
88
+ schedule it twice or count it twice toward `npending`, since asyncio.gather
89
+ has the same behavior for repeated arguments.
90
+
91
+ On 3.14+, `future_add_to_awaited_by`/`future_discard_from_awaited_by` keep
92
+ each child's "awaited by" introspection link pointed at the *caller's*
93
+ task instead of this function's internal bookkeeping -- otherwise tools
94
+ like asyncio's task graph (or Task.print_stack()) would show the children
95
+ as awaited by a frame that already returned.
96
+ """
97
+
98
+ if not awaitables:
99
+ outer = asyncio.get_event_loop().create_future()
100
+ outer.set_result([])
101
+ return outer
102
+
103
+ if _PY314:
104
+ loop = _get_running_loop()
105
+ current_task = None if loop is None else asyncio.current_task(loop)
106
+ else:
107
+ loop = None
108
+ current_task = None
109
+
110
+
111
+ def _done_callback(fut, current_task = current_task):
112
+ nonlocal npending
113
+ npending -= 1
114
+
115
+ if _PY314 and current_task is not None:
116
+ asyncio.future_discard_from_awaited_by(fut, current_task)
117
+
118
+ if outer is None or outer.done():
119
+ if not fut.cancelled():
120
+ fut.exception() # استهلاك الاستثناء لمنع تحذير asyncio
121
+ return
122
+
123
+ if not return_exceptions:
124
+ try:
125
+ exc = fut.exception()
126
+ except asyncio.CancelledError as e:
127
+ exc = e
128
+
129
+ if exc is not None:
130
+ outer.set_exception(exc)
131
+
132
+ for child in children:
133
+ if child is not fut and not child.done():
134
+ child.cancel()
135
+
136
+ return
137
+
138
+ if npending == 0:
139
+ results = []
140
+
141
+ for child in children:
142
+ try:
143
+ result = child.exception()
144
+ except asyncio.CancelledError as e:
145
+ result = e
146
+
147
+ if result is None:
148
+ result = child.result()
149
+
150
+ results.append(result)
151
+
152
+ if (cancel_message := outer.cancel_message) is not None:
153
+ outer.set_exception(asyncio.CancelledError(cancel_message))
154
+ else:
155
+ outer.set_result(results)
156
+
157
+
158
+
159
+ npending = 0
160
+ outer = None
161
+
162
+ done_futs = []
163
+ children = []
164
+
165
+ awaitable_2_fut = {}
166
+
167
+
168
+ for awaitable in awaitables:
169
+ fut = awaitable_2_fut.get(awaitable)
170
+
171
+ if fut is None:
172
+ fut = asyncio.ensure_future(awaitable, loop=loop)
173
+
174
+ if loop is None:
175
+ loop = _get_fut_loop(fut)
176
+
177
+ if fut is not awaitable:
178
+ fut._log_destroy_pending = False
179
+
180
+ npending += 1
181
+ awaitable_2_fut[awaitable] = fut
182
+
183
+ if fut.done():
184
+ done_futs.append(fut)
185
+ else:
186
+ if _PY314 and current_task is not None:
187
+ asyncio.future_add_to_awaited_by(fut, current_task)
188
+
189
+ fut.add_done_callback(_done_callback)
190
+
191
+ children.append(fut)
192
+
193
+ outer = _GatheringFuture(children, loop=loop)
194
+
195
+ for fut in done_futs:
196
+ _done_callback(fut)
197
+
198
+ return outer
199
+
200
+
201
+
202
+