Metadata-Version: 2.4
Name: tinyio
Version: 0.4.0
Summary: A tiny event loop for Python.
Project-URL: repository, https://github.com/patrick-kidger/tinyio
Author-email: Patrick Kidger <contact@kidger.site>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: async,asyncio,await,tinyio
Classifier: Development Status :: 3 - Alpha
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.11
Provides-Extra: dev
Requires-Dist: pre-commit; extra == 'dev'
Provides-Extra: tests
Requires-Dist: pytest; extra == 'tests'
Requires-Dist: trio; extra == 'tests'
Description-Content-Type: text/markdown

<h1 align="center">tinyio</h1>
<h2 align="center">A tiny (~400 lines) event loop for Python</h2>

_Ever used `asyncio` and wished you hadn't?_

`tinyio` is a dead-simple event loop for Python, born out of my frustration with trying to get robust error handling with `asyncio`. (I'm not the only one running into its sharp corners: [link1](https://sailor.li/asyncio), [link2](https://lucumr.pocoo.org/2016/10/30/i-dont-understand-asyncio/).)

This is an alternative for the simple use-cases, where you just need an event loop, and want to crash the whole thing if anything goes wrong. (Raising an exception in every coroutine so it can clean up its resources.)

```python
import tinyio

def slow_add_one(x: int):
    yield tinyio.sleep(1)
    return x + 1

def foo():
    four, five = yield [slow_add_one(3), slow_add_one(4)]
    return four, five

loop = tinyio.Loop()
out = loop.run(foo())
assert out == (4, 5)
```

- Somewhat unusually, our syntax uses `yield` rather than `await`, but the behaviour is the same. Await another coroutine with `yield coro`. Await on multiple with `yield [coro1, coro2, ...]` (a 'gather' in `asyncio` terminology; a 'nursery' in `trio` terminology).
- An error in one coroutine will cancel all coroutines across the entire event loop.
    - If the erroring coroutine is sequentially depended on by a chain of other coroutines, then we chain their tracebacks for easier debugging.
    - Errors propagate to and from synchronous operations ran in threads.
- Can nest tinyio loops inside each other, none of this one-per-thread business.
- Ludicrously simple. No need for futures, tasks, etc. Here's the entirety of the day-to-day API:
    ```python
    tinyio.Loop
    tinyio.run_in_thread
    tinyio.sleep
    tinyio.CancelledError
    ```

## Installation

```
pip install tinyio
```

## Documentation

### Loops

Create a loop with `tinyio.Loop()`. It has a single method, `.run(coro)`, which consumes a coroutine, and which returns the output of that coroutine.

Coroutines can `yield` four possible things:

- `yield`: yield nothing, this just pauses and gives other coroutines a chance to run.
- `yield coro`: wait on a single coroutine, in which case we'll resume with the output of that coroutine once it is available.
- `yield [coro1, coro2, coro3]`: wait on multiple coroutines by putting them in a list, and resume with a list of outputs once all have completed. This is what `asyncio` calls a 'gather' or 'TaskGroup', and what `trio` calls a 'nursery'.
- `yield {coro1, coro2, coro3}`: schedule one or more coroutines but do not wait on their result - they will run independently in the background.

If you `yield` on the same coroutine multiple times (e.g. in a diamond dependency pattern) then the coroutine will be scheduled once, and on completion all dependees will receive its output. (You can even do this if the coroutine has already finished: `yield` on it to retrieve its output.)

### Threading

Blocking functions can be ran in threads using `tinyio.run_in_thread(fn, *args, **kwargs)`, which gives a coroutine you can `yield` on. Example:

```python
import time, tinyio

def slow_blocking_add_one(x: int) -> int:
    time.sleep(1)
    return x + 1

def foo(x: int):
    out = yield [tinyio.run_in_thread(slow_blocking_add_one, x) for _ in range(3)]
    return out

loop = tinyio.Loop()
out = loop.run(foo(x=1))  # runs in one second, not three
assert out == [2, 2, 2]
```

### Sleeping

This is `tinyio.sleep(delay_in_seconds)`, which is a coroutine you can `yield` on.

### Error propagation

If any coroutine raises an error, then:

1. All coroutines across the entire loop will have `tinyio.CancelledError` raised in them (from whatever `yield` point they are currently waiting at).
2. Any functions ran in threads via `tinyio.run_in_thread` will also have `tinyio.CancelledError` raised in the thread.
3. The original error is raised out of `loop.run(...)`. This behaviour can be configured (e.g. to collect errors into a `BaseExceptionGroup`) by setting `loop.run(..., exception_group=None/False/True)`.

This gives every coroutine a chance to shut down gracefully. Debuggers like [`patdb`](https://github.com/patrick-kidger/patdb) offer the ability to navigate across exceptions in an exception group, allowing you to inspect the state of all coroutines that were related to the error.

### Synchronisation

We ship batteries-included with the usual collection of standard operations for synchronisation.

<details><summary>Click to expand</summary>

```python
tinyio.as_completed       tinyio.Semaphore
tinyio.Barrier            tinyio.ThreadPool
tinyio.Event              tinyio.timeout
tinyio.Lock               tinyio.TimeoutError
```

---

- `tinyio.as_completed({coro1, coro2, ...})`

    This schedules multiple coroutines in the background (like `yield {coro1, coro2, ...}`), and then offers their results in the order they complete.

    This is iterated over in the following way, using its `.done()` and `.get()` methods:
    ```python
    def main():
        iterator = yield tinyio.as_completed({coro1, coro2, coro3})
        for next_coro in iterator:
            result = yield next_coro
    ```

---

- `tinyio.Barrier(value)`

    This has a single method `barrier.wait()`, which is a coroutine you can `yield` on. Once `value` many coroutines have yielded on this method then it will unblock.

---

- `tinyio.Event()`

    This is a wrapper around a boolean flag, initialised with `False`.
    This has the following methods:
    
    - `.is_set()`: return the value of the flag.
    - `.set()`: set the flag to `True`.
    - `.clear()`: set the flag to `False`.
    - `.wait(timeout_in_seconds=None)`, which is a coroutine you can `yield` on. This will unblock if the internal flag is `True` or if `timeout_in_seconds` seconds pass. (Typically the former is accomplished by calling `.set()` from another coroutine or from a thread.)

---

- `tinyio.Lock()`

    This is just a convenience for `tinyio.Semaphore(value=1)`, see below.

---

- `tinyio.Semaphore(value)`

    This manages an internal counter that is initialised at `value`, is decremented when entering a region, and incremented when exiting. This blocks if this counter is at zero. In this way, at most `value` coroutines may acquire the semaphore at a time.

    This is used as:
    ```python
    semaphore = Semaphore(value)

    ...

    with (yield semaphore()):
        ...
    ```

---

- `tinyio.timeout(coro, timeout_in_seconds)`

    This is a coroutine you can `yield` on, used as `output, success = yield tinyio.timeout(coro, timeout_in_seconds)`.
    
    This runs `coro` for at most `timeout_in_seconds`. If it succeeds in that time then the pair `(output, True)` is returned . Else this will return `(None, False)`, and `coro` will be halted by raising `tinyio.TimeoutError` inside it.

---

- `tinyio.ThreadPool(max_threads)`

    This is equivalent to making multiple `tinyio.run_in_thread` calls, but will limit the number of threads to at most `max_threads`. Additional work after that will block until a thread becomes available.

    This has two methods:

    - `.run_in_thread(fn, *args, **kwargs)`, which is a coroutine you can `yield` on. This is equivalent to `yield tinyio.run_in_thread(fn, *args, **kwargs)`.
    - `.map(fn, xs)`, which is a coroutine you can `yield` on. This is equivalent to `yield [tinyio.run_in_thread(fn, x) for x in xs]`.
 
---

</details>

### Asynchronous context managers

<details><summary>Click to expand</summary>

You can use the following pattern to implement context managers with asynchronous creation:

```python
import contextlib
import tinyio

def my_context_manager(x):
    print("Initialising...")
    yield tinyio.sleep(1)
    print("Initialised")
    return make_context_manager(x)

@contextlib.contextmanager
def make_context_manager(x):
    try:
        yield x
    finally:
        print("Cleaning up")

def my_coro():
    with (yield my_context_manager(x=5)) as val:
        print(f"Got val {val}")

tinyio.Loop().run(my_coro())
```

This isn't anything fancier than just using a coroutine that returns a regular `with`-compatible context manager. See `tinyio.Semaphore` for an example of this pattern.

</details>

### Asynchronous iterators

<details><summary>Click to expand</summary>

You can use the following pattern to implement asychronous iterators:

```python
import tinyio

def slow_range(x):  # this function is an iterator-of-coroutines
for i in range(x):
    yield slow_range_i(i)  # this `yield` statement is seen by the `for` loop

def slow_range_i(i):  # this function is a coroutine
yield tinyio.sleep(1)  # this `yield` statement is seen by the `tinyio.Loop()`
return i

def my_coro():
for x in slow_range(5):
    x = yield x
    print(f"Got {x}")

tinyio.Loop().run(my_coro())
```

Here we just have `yield` being used in a couple of different ways that you're already used to:
- as a regular Python generator/iterator;
- as a `tinyio` coroutine.

For an example of this, see `tinyio.as_completed`.

</details>

### Integration with `asyncio` and `trio`

We have support for putting `trio` event loops within `asyncio`/`trio` event loops, or vice-versa.

<details><summary>Click to expand</summary>

```python
tinyio.to_asyncio         tinyio.to_trio
tinyio.from_asyncio       tinyio.from_trio
```

---

- `tinyio.to_asyncio(coro, exception_group=None)`

    This converts a `tinyio` coroutine into an `asyncio` coroutine.

    For example:
    ```python
    def add_one(x):
        yield tinyio.sleep(1)
        return x + 1

    async def foo(x):
        y = await tinyio.to_asyncio(add_one(x))
        return y

    asyncio.run(foo(3))
    ```

---

- `tinyio.from_asyncio(coro)`

    This converts an `asyncio` coroutine into a `tinyio` coroutine.

    > WARNING!  
    > This works by running the entire `asyncio` portion in a separate thread. This may lead to surprises if the `asyncio` and non-`asyncio` portions interact in non-threadsafe ways.

    For example:
    ```python
    async def add_one(x):
        await asyncio.sleep(1)
        return x + 1

    def foo(x):
        y = yield tinyio.from_asyncio(add_one(x))
        return y

    tinyio.Loop().run(foo(3))
    ```

---

- `tinyio.to_trio(coro, exception_group=None)`

    This converts a `tinyio` coroutine into an `trio` coroutine.

    For example:
    ```python
    def add_one(x):
        yield tinyio.sleep(1)
        return x + 1

    async def foo(x):
        y = await tinyio.to_trio(add_one(x))
        return y

    trio.run(foo, 3)
    ```

---

- `tinyio.from_trio(async_fn, *args)`

    This converts an `trio` coroutine into a `tinyio` coroutine.

    For example:
    ```python
    async def add_one(x):
        await trio.sleep(1)
        return x + 1

    def foo(x):
        y = yield tinyio.from_trio(add_one, x)
        return y

    tinyio.Loop().run(foo(3))
    ```

---

</details>

### Advanced topic: isolating coroutines without crashing the others

<details><summary>Click to expand</summary>

If you would like to run a coroutine (and transitively, all the coroutines it `yield`s) without crashing the entire event loop, then you can use `tinyio.isolate`. This will run the coroutine in a nested `tinyio.Loop` – so that it crashing will only affect everything in that nested loop – and then return the result or the error.

```python
def some_coroutine(x):
    if x == 3:
        raise ValueError("Oh no, a bug!")
    yield

def someone_elses_buggy_code():
    yield [some_coroutine(x=3), another_coroutine()]

def main():
    app = someone_elses_buggy_code()
    result_or_error, success = yield tinyio.isolate(app)
    # at this point then `someone_elses_buggy_code`, `some_coroutine` and
    #`another_coroutine` have been cancelled, but `main` is still running.
```

</details>

## FAQ

<details>
<summary>Why <code>yield</code> - why not <code>await</code> like is normally seen for coroutines?</summary>
<br>

The reason is that `await` does not offer a suspension point to an event loop (it just calls `__await__` and maybe *that* offers a suspension point), so if we wanted to use that syntax then we'd need to replace `yield coro` with something like `await tinyio.Task(coro)`. The traditional syntax is not worth the extra class.
</details>

<details>
<summary>I have a function I want to be a coroutine, but it has zero <code>yield</code> statements, so it is just a normal function?</summary>
<br>

You can distinguish it from a normal Python function by putting `if False: yield` somewhere inside its body. Another common trick is to put a `yield` statement after the final `return` statement. Bit ugly but oh well.
</details>

<details>
<summary>vs <code>asyncio</code> or <code>trio</code>?</summary>
<br>

I wasted a *lot* of time trying to get correct error propagation with `asyncio`, trying to reason whether my tasks would be cleaned up correctly or not (edge-triggered vs level-triggered etc etc). `trio` is excellent but still has a one-loop-per-thread rule, and doesn't propagate cancellations to/from threads. These points inspired me to try writing my own.

`tinyio` has the following unique features, and as such may be the right choice if any of the following are must-haves for you:

- the propagation of errors to/from threads;
- no one-loop-per-thread rule;
- simple+robust error semantics (crash the whole loop if anything goes wrong);
- tiny, hackable, codebase.

Conversely, at least right now we don't ship batteries-included with a few things:

- asynchronously launching subprocesses / making network requests / accessing the file system (in all cases use `run_in_thread` instead);
- scheduling work on the event loop whilst cleaning up from errors.

If none of the bullet points are must-haves for you, or if any of its limitations are dealbreakers, then either `trio` or `asyncio` are likely to be better choices. :)

</details>
