fr-async 0.1.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.
@@ -0,0 +1,131 @@
1
+ # PolyForm Noncommercial License 1.0.0
2
+
3
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
4
+
5
+ ## Acceptance
6
+
7
+ In order to get any license under these terms, you must agree
8
+ to them as both strict obligations and conditions to all
9
+ your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the
14
+ software to do everything you might do with the software
15
+ that would otherwise infringe the licensor's copyright
16
+ in it for any permitted purpose. However, you may
17
+ only distribute the software according to [Distribution
18
+ License](#distribution-license) and make changes or new works
19
+ based on the software according to [Changes and New Works
20
+ License](#changes-and-new-works-license).
21
+
22
+ ## Distribution License
23
+
24
+ The licensor grants you an additional copyright license
25
+ to distribute copies of the software. Your license
26
+ to distribute covers distributing the software with
27
+ changes and new works permitted by [Changes and New Works
28
+ License](#changes-and-new-works-license).
29
+
30
+ ## Notices
31
+
32
+ You must ensure that anyone who gets a copy of any part of
33
+ the software from you also gets a copy of these terms or the
34
+ URL for them above, as well as copies of any plain-text lines
35
+ beginning with `Required Notice:` that the licensor provided
36
+ with the software. For example:
37
+
38
+ > Required Notice: Copyright Yoyodyne, Inc. (<http://example.com>)
39
+
40
+ ## Changes and New Works License
41
+
42
+ The licensor grants you an additional copyright license to
43
+ make changes and new works based on the software for any
44
+ permitted purpose.
45
+
46
+ ## Patent License
47
+
48
+ The licensor grants you a patent license for the software that
49
+ covers patent claims the licensor can license, or becomes able
50
+ to license, that you would infringe by using the software.
51
+
52
+ ## Noncommercial Purposes
53
+
54
+ Any noncommercial purpose is a permitted purpose.
55
+
56
+ ## Personal Uses
57
+
58
+ Personal use for research, experiment, and testing for
59
+ the benefit of public knowledge, personal study, private
60
+ entertainment, hobby projects, amateur pursuits, or religious
61
+ observance, without any anticipated commercial application,
62
+ is use for a permitted purpose.
63
+
64
+ ## Noncommercial Organizations
65
+
66
+ Use by any charitable organization, educational institution,
67
+ public research organization, public safety or health
68
+ organization, environmental protection organization,
69
+ or government institution is use for a permitted purpose
70
+ regardless of the source of funding or obligations resulting
71
+ from the funding.
72
+
73
+ ## Fair Use
74
+
75
+ You may have "fair use" rights for the software under the
76
+ law. These terms do not limit them.
77
+
78
+ ## No Other Rights
79
+
80
+ These terms do not allow you to sublicense or transfer any of
81
+ your licenses to anyone else, or prevent the licensor from
82
+ granting licenses to anyone else. These terms do not imply
83
+ any other licenses.
84
+
85
+ ## Patent Defense
86
+
87
+ If you make any written claim that the software infringes or
88
+ contributes to infringement of any patent, your patent license
89
+ for the software granted under these terms ends immediately. If
90
+ your company makes such a claim, your patent license ends
91
+ immediately for work on behalf of your company.
92
+
93
+ ## Violations
94
+
95
+ The first time you are notified in writing that you have
96
+ violated any of these terms, or done anything with the software
97
+ not covered by your licenses, your licenses can nonetheless
98
+ continue if you come into full compliance with these terms,
99
+ and take practical steps to correct past violations, within
100
+ 32 days of receiving notice. Otherwise, all your licenses
101
+ end immediately.
102
+
103
+ ## No Liability
104
+
105
+ ***As far as the law allows, the software comes as is, without
106
+ any warranty or condition, and the licensor will not be liable
107
+ to you for any damages arising out of these terms or the use
108
+ or nature of the software, under any kind of legal claim.***
109
+
110
+ ## Definitions
111
+
112
+ The **licensor** is the individual or entity offering these
113
+ terms, and the **software** is the software the licensor makes
114
+ available under these terms.
115
+
116
+ **You** refers to the individual or entity agreeing to these
117
+ terms.
118
+
119
+ **Your company** is any legal entity, sole proprietorship,
120
+ or other kind of organization that you work for, plus all
121
+ organizations that have control over, are under the control of,
122
+ or are under common control with that organization. **Control**
123
+ means ownership of substantially all the assets of an entity,
124
+ or the power to direct its management and policies by vote,
125
+ contract, or otherwise. Control can be direct or indirect.
126
+
127
+ **Your licenses** are all the licenses granted to you for the
128
+ software under these terms.
129
+
130
+ **Use** means anything you do with the software requiring one
131
+ of your licenses.
@@ -0,0 +1,29 @@
1
+ Metadata-Version: 2.4
2
+ Name: fr-async
3
+ Version: 0.1.0
4
+ Summary: Async but with yield instead of await
5
+ Author-email: Omena0 <omena0mc@gmail.com>
6
+ License-Expression: LicenseRef-PolyForm-Noncommercial-1.0.0
7
+ Project-URL: Homepage, https://github.com/Omena0/fr-async
8
+ Project-URL: Repository, https://github.com/Omena0/fr-async
9
+ Project-URL: Issues, https://github.com/Omena0/fr-async/issues
10
+ Keywords: async,asyncio,concurrency,event-loop,generators,cooperative-multitasking
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.15
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Topic :: System :: Networking
18
+ Requires-Python: >=3.15
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE.md
21
+ Dynamic: license-file
22
+
23
+ # fr-async
24
+
25
+ [![Lint](https://github.com/Omena0/fr-async/actions/workflows/lint.yml/badge.svg)](https://github.com/Omena0/fr-async/actions/workflows/lint.yml)
26
+ [![Test](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/Omena0/fr-async/main/.github/badges/test-score.json)](https://github.com/Omena0/fr-async/actions/workflows/test.yml)
27
+ [![PyPI](https://github.com/Omena0/fr-async/actions/workflows/publish.yml/badge.svg)](https://github.com/Omena0/fr-async/actions/workflows/publish.yml)
28
+
29
+ Async but with yield instead of await
@@ -0,0 +1,7 @@
1
+ # fr-async
2
+
3
+ [![Lint](https://github.com/Omena0/fr-async/actions/workflows/lint.yml/badge.svg)](https://github.com/Omena0/fr-async/actions/workflows/lint.yml)
4
+ [![Test](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/Omena0/fr-async/main/.github/badges/test-score.json)](https://github.com/Omena0/fr-async/actions/workflows/test.yml)
5
+ [![PyPI](https://github.com/Omena0/fr-async/actions/workflows/publish.yml/badge.svg)](https://github.com/Omena0/fr-async/actions/workflows/publish.yml)
6
+
7
+ Async but with yield instead of await
@@ -0,0 +1,17 @@
1
+ """Cooperative asynchronous programming with generators and yielded messages."""
2
+
3
+ from .classes import File, Task, TaskGroup, Yieldable
4
+ from .loop import ExecutionLoop, getEventLoop
5
+ from .scheduler import EEVDFScheduler
6
+ from . import messages
7
+
8
+ __all__ = [
9
+ 'EEVDFScheduler',
10
+ 'ExecutionLoop',
11
+ 'File',
12
+ 'Task',
13
+ 'TaskGroup',
14
+ 'Yieldable',
15
+ 'getEventLoop',
16
+ 'messages'
17
+ ]
@@ -0,0 +1,30 @@
1
+
2
+
3
+ from typing import Any
4
+
5
+ from .classes import Task, Yieldable
6
+ from .loop import ExecutionLoop
7
+ from .messages import *
8
+ from .scheduler import EEVDFScheduler
9
+
10
+
11
+ def gen():
12
+ yield Sleep(1)
13
+ print('1')
14
+ yield Sleep(1)
15
+ print('2')
16
+ yield Sleep(1)
17
+ print('3')
18
+
19
+ def main() -> Any:
20
+ yield Task(gen(), background=True)
21
+ print('a')
22
+ yield Sleep(1)
23
+ print('b')
24
+ yield Sleep(1)
25
+ print('c')
26
+ yield Sleep(1)
27
+ print('d')
28
+
29
+ loop: ExecutionLoop = ExecutionLoop(EEVDFScheduler)
30
+ loop.run(Yieldable(main))
@@ -0,0 +1,330 @@
1
+ import inspect
2
+ import os
3
+ from collections import deque
4
+ from collections.abc import Callable, Generator
5
+ from contextvars import Context, copy_context
6
+ from os import PathLike
7
+ from typing import IO, Any, Final, Literal, Self, TypeIs, overload
8
+
9
+ lazy from .loop import getEventLoop
10
+ lazy from .messages import (
11
+ FileRead,
12
+ FileWrite,
13
+ Message,
14
+ TaskGroupAsCompleted,
15
+ TaskGroupCollect,
16
+ TaskJoin,
17
+ check_resolved,
18
+ )
19
+ lazy from .utils import log
20
+
21
+
22
+ class _Missing:
23
+ """Sentinel type used to distinguish a missing value."""
24
+ __slots__ = ()
25
+
26
+ _MISSING = _Missing()
27
+
28
+ class Assignable:
29
+ 'Store arbitrary data and expose entries as attributes.'
30
+ __slots__ = ('_data',)
31
+
32
+ def __init__(self) -> None:
33
+ 'Create an empty attribute store.'
34
+ self._data: dict[Any, Any] = {}
35
+
36
+ def __setattr__(self, name: str, value: Any) -> None:
37
+ 'Store user attributes in the internal mapping.'
38
+ if name == '_data':
39
+ return super().__setattr__(name, value)
40
+
41
+ self._data[name] = value
42
+ return None
43
+
44
+ def __getattr__(self, name: str):
45
+ 'Look up an attribute in the internal mapping.'
46
+ try:
47
+ return self._data[name]
48
+ except KeyError:
49
+ raise AttributeError(name) from None
50
+
51
+ def update(self, data: dict[Any, Any]):
52
+ 'Merge entries into the attribute store.'
53
+ self._data |= data
54
+
55
+ def _is_generator(x: Any) -> TypeIs[Generator[Any, Any, Any]]:
56
+ 'Return whether a value is a generator object.'
57
+ return inspect.isgenerator(x)
58
+
59
+ # Tasks
60
+ class Task[T=Any]:
61
+ 'Represent a callable or generator managed by the event loop.'
62
+ __slots__ = (
63
+ '_context',
64
+ '_joiners',
65
+ '_return_val',
66
+ '_stop_requested',
67
+ '_throw_val',
68
+ '_timeout_deadline',
69
+ '_timeout_expired',
70
+ '_timeout_started',
71
+ 'args',
72
+ 'background',
73
+ 'data',
74
+ 'done',
75
+ 'exception',
76
+ 'func',
77
+ 'immediate',
78
+ 'kwargs',
79
+ 'parent',
80
+ 'result',
81
+ 'timeout',
82
+ 'wait_for',
83
+ )
84
+
85
+ def __init__(self, func: Generator[Any, Any, T] | Callable[..., T], *args: Any, background=False, immediate=False, parent: Task | None = None, data: dict[Any, Any] | None = None, timeout: float | None = None, **kwargs: Any):
86
+ 'Initialize the task and its optional timeout, measured from its first run.'
87
+ if timeout is not None and timeout < 0:
88
+ raise ValueError('Task timeout must be non-negative.')
89
+
90
+ self.func: Generator[Any, Any, Any] | Callable[..., Any] = func
91
+ self.immediate = immediate
92
+ self.background = background
93
+
94
+ self.args = args
95
+ self.kwargs = kwargs
96
+
97
+ self.parent: Task | None = parent
98
+ self.done = False
99
+ self.result: Any = None
100
+ self.exception: BaseException | None = None
101
+ self.timeout = timeout
102
+ self._timeout_deadline: float | None = None
103
+ self._timeout_started = False
104
+ self._timeout_expired = False
105
+ self._joiners: list[tuple[Message, Task]] = []
106
+
107
+ self.data = Assignable()
108
+ self.data.update(data or {})
109
+
110
+ self._stop_requested = False
111
+ self._return_val: Any = _MISSING
112
+ self._throw_val: Any = _MISSING
113
+
114
+ self.wait_for: deque[Message] = deque()
115
+ self._context: Context = copy_context()
116
+
117
+ def __call__(self) -> T | None:
118
+ 'Advance the generator or invoke the callable and return its yielded value.'
119
+ if self._stop_requested:
120
+ if _is_generator(self.func):
121
+ self.func.close()
122
+
123
+ self.done = True
124
+ self.result = None
125
+ return None
126
+
127
+ if _is_generator(self.func):
128
+ try:
129
+ if isinstance(self._throw_val, BaseException):
130
+ exc = self._throw_val
131
+ self._throw_val = _MISSING
132
+ self._timeout_expired = False
133
+ return self.func.throw(exc)
134
+
135
+ if self._return_val is not _MISSING:
136
+ value = self._return_val
137
+ self._return_val = _MISSING
138
+ return self.func.send(value)
139
+
140
+ return next(self.func)
141
+
142
+ except StopIteration as e:
143
+ self.done = True
144
+ self.result = e.value
145
+ return e.value
146
+
147
+ result = self.func(*self.args, **self.kwargs)
148
+ self.done = True
149
+ self.result = result
150
+ return result
151
+
152
+ def __repr__(self) -> str:
153
+ 'Return a readable representation of the task.'
154
+ name: str = getattr(self.func, '__name__', str(self.func))
155
+ return f"Task({name}, {self.args}, {self.kwargs})"
156
+
157
+ @property
158
+ def is_ready(self):
159
+ 'Return whether all messages blocking this task are resolved.'
160
+ return check_resolved(self.wait_for)
161
+
162
+ def throw_value(self, exc: Any):
163
+ 'Schedule an exception to throw into the task generator.'
164
+ self._throw_val = exc
165
+
166
+ def return_value(self, value: Any):
167
+ 'Schedule a value to send into the task generator.'
168
+ log(f'Task returned {value} to {self}')
169
+ self._return_val = value
170
+
171
+ def stop(self):
172
+ 'Request that the task stop when it next runs.'
173
+ self._stop_requested = True
174
+
175
+ def join(self, *, background: bool = False) -> TaskJoin[T]:
176
+ """Wait for this task to finish and return its result."""
177
+ return TaskJoin(self, background=background)
178
+
179
+ # Task factory function wrapper
180
+ class Yieldable:
181
+ 'Wrap a callable so it can be converted into an event loop task.'
182
+ __slots__ = ('func',)
183
+
184
+ def __init__(self, func: Callable[..., Any]):
185
+ 'Store the callable to wrap.'
186
+ self.func = func
187
+
188
+ def __call__(self, /, *args: Any, background: bool=False, immediate=False, data: dict[Any, Any] | None = None, timeout: float | None = None, **kwargs: Any) -> Task:
189
+ 'Create a task with scheduling options and an optional first-run timeout.'
190
+ if inspect.isgeneratorfunction(self.func):
191
+ return Task(self.func(*args, **kwargs), background=background, immediate=immediate, timeout=timeout)
192
+
193
+ return Task(self.func, background=background, immediate=immediate, data=data, timeout=timeout, *args, **kwargs)
194
+
195
+ def __repr__(self) -> str:
196
+ 'Return a readable representation of the wrapped callable.'
197
+ return f"Yieldable({self.func.__name__})"
198
+
199
+ # File wrapper
200
+ type FilePath = str | PathLike[str]
201
+ type OpenTextMode = Literal['r', 'w', 'a', 'x', 'r+', 'w+', 'a+', 'x+']
202
+ type OpenBinaryMode = Literal['rb', 'wb', 'ab', 'xb', 'rb+', 'wb+', 'ab+', 'xb+']
203
+ type OpenMode = OpenTextMode | OpenBinaryMode
204
+
205
+ class File[T: (str, bytes)]:
206
+ 'Wrap a text or binary file and expose event loop file operations.'
207
+ __slots__ = ('_binary', '_file')
208
+
209
+ @overload
210
+ def __init__(
211
+ self: File[bytes],
212
+ path: FilePath,
213
+ mode: OpenBinaryMode,
214
+ buffering: int = -1,
215
+ encoding: str | None = None,
216
+ errors: str | None = None,
217
+ newline: str | None = None,
218
+ closefd: bool = True,
219
+ opener: Callable[[str, int], int] | None = None
220
+ ) -> None:
221
+ """Typing overload for opening a binary file."""
222
+ @overload
223
+ def __init__(
224
+ self: File[str],
225
+ path: FilePath,
226
+ mode: OpenTextMode,
227
+ buffering: int = -1,
228
+ encoding: str | None = None,
229
+ errors: str | None = None,
230
+ newline: str | None = None,
231
+ closefd: bool = True,
232
+ opener: Callable[[str, int], int] | None = None
233
+ ) -> None:
234
+ """Typing overload for opening a text file."""
235
+ def __init__(
236
+ self,
237
+ path: FilePath,
238
+ mode: OpenMode,
239
+ buffering: int = -1,
240
+ encoding: str | None = None,
241
+ errors: str | None = None,
242
+ newline: str | None = None,
243
+ closefd: bool = True,
244
+ opener: Callable[[str, int], int] | None = None
245
+ ):
246
+ 'Open a file using the requested mode and options.'
247
+ self._file: Final[IO[T]] = open(path, mode, buffering, encoding, errors, newline, closefd, opener)
248
+ self._binary = 'b' in mode
249
+
250
+ def write(self, data: T, *, background: bool = False) -> FileWrite[T]:
251
+ 'Create a message that writes data to the file.'
252
+ return FileWrite[T](self._file, data, background=background)
253
+
254
+ def read(self, n: int = -1, *, background: bool = False) -> FileRead[T]:
255
+ 'Create a message that reads from the current file position.'
256
+ return FileRead[T](self._file, n, background=background)
257
+
258
+ def seek(self, offset: int, whence: int = 0) -> int:
259
+ 'Move the file cursor and return its new position.'
260
+ return self._file.seek(offset, whence)
261
+
262
+ def delete(self):
263
+ 'Remove the file from the filesystem.'
264
+ os.remove(self._file.name)
265
+
266
+ def __enter__(self) -> Self:
267
+ return self
268
+
269
+ def __exit__(self, *_):
270
+ self._file.close()
271
+
272
+ # Task group
273
+ class TaskGroup:
274
+ 'Collect tasks for coordinated scheduling, cancellation, and result handling.'
275
+ __slots__ = ('started', 'tasks')
276
+
277
+ def __init__(self) -> None:
278
+ 'Create an empty task group that has not started.'
279
+ self.tasks: list[Task] = []
280
+ self.started = False
281
+
282
+ def add(self, task: Task, autorun: bool = True) -> Task:
283
+ 'Add a task, scheduling it if a started group autoruns additions.'
284
+ if task in self.tasks:
285
+ return task
286
+
287
+ self.tasks.append(task)
288
+
289
+ if autorun and self.started and not task.done:
290
+ getEventLoop().schedule(task)
291
+
292
+ return task
293
+
294
+ def collect(self, *, background: bool = False) -> TaskGroupCollect[Any]:
295
+ 'Create a message that returns results in group order.'
296
+ return TaskGroupCollect(tuple(self.tasks), background=background)
297
+
298
+ def as_completed(self, *, background: bool = False) -> TaskGroupAsCompleted[Any]:
299
+ 'Create a message that yields results in completion order.'
300
+ return TaskGroupAsCompleted(tuple(self.tasks), background=background)
301
+
302
+ def cancel(self):
303
+ 'Request that every task in the group stop.'
304
+ for task in self.tasks:
305
+ task.stop()
306
+
307
+ def run(self, background: bool = False) -> TaskGroupCollect[Any] | None:
308
+ 'Schedule unfinished tasks and optionally return a collection message.'
309
+ loop = getEventLoop()
310
+ self.started = True
311
+ for task in self.tasks:
312
+ if not task.done:
313
+ loop.schedule(task)
314
+ return None if background else self.collect()
315
+
316
+ def join(self, *, background: bool = False) -> TaskGroupCollect[Any]:
317
+ """Wait for all group tasks; use as ``yield group.join()``."""
318
+ return self.collect(background=background)
319
+
320
+ def __iter__(self):
321
+ 'Iterate over tasks in insertion order.'
322
+ return iter(self.tasks)
323
+
324
+ def __len__(self) -> int:
325
+ 'Return the number of tasks in the group.'
326
+ return len(self.tasks)
327
+
328
+ def __contains__(self, task: object) -> bool:
329
+ 'Return whether a task belongs to this group.'
330
+ return task in self.tasks
@@ -0,0 +1,10 @@
1
+
2
+ # Exceptions
3
+ class NoEventLoopException(Exception):
4
+ __slots__ = ()
5
+
6
+ class TaskTimeoutError(TimeoutError):
7
+ __slots__ = ()
8
+
9
+ """Raised when a task exceeds its configured timeout."""
10
+