invoke asyncio awaitables from non-async functions
Project description
Call Python asyncio awaitables from functions that are not declared as async.
Synopsis
Consider the following asyncio program that sends and receives messages from an echo server:
import asyncio async def sendrecv(msg): reader, writer = await asyncio.open_connection("tcpbin.com", 4242) writer.write(f"message number {msg}\n".encode("ascii")) await writer.drain() data = (await reader.read(1024)).decode("utf-8") return data async def main(): messages = await asyncio.gather( *[ sendrecv(msg) for msg in ["one", "two", "three", "four", "five"] ] ) for msg in messages: print(f"Got back echo response: {msg}") asyncio.run(main())
What if sendrecv above wanted to be a function available in existing code that didn’t use async? With awaitlet we can remove the async keyword and still have a way of invoking async awaitables inside of it:
import asyncio from awaitlet import async_def from awaitlet import awaitlet def sendrecv_implementation(msg): reader, writer = awaitlet(asyncio.open_connection("tcpbin.com", 4242)) writer.write(f"message number {msg}\n".encode("ascii")) awaitlet(writer.drain()) data = (awaitlet(reader.read(1024))).decode("utf-8") return data async def sendrecv(msg): return await async_def(sendrecv_implementation, msg) async def main(): messages = await asyncio.gather( *[ sendrecv(msg) for msg in ["one", "two", "three", "four", "five"] ] ) for msg in messages: print(f"Got back echo response: {msg}") asyncio.run(main())
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
awaitlet-0.0.0.tar.gz
(12.3 kB
view details)
File details
Details for the file awaitlet-0.0.0.tar.gz
.
File metadata
- Download URL: awaitlet-0.0.0.tar.gz
- Upload date:
- Size: 12.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.10.13
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | e8e6ba4d3535ef82fef6de025d2c0ae82cef48a675875f743eb89d34110142be |
|
MD5 | 6b0802df4c03c3a4736c9b775adb006c |
|
BLAKE2b-256 | db879c05e8423897ca465c348cf94090de66517b514f9d7bc0b3c64edb02f029 |