Skip to main content

Idiomatic asyncio utilities

Project description

PyPI version Python Versions Build Status Code Coverage

Idiomatic asyncio utilties

Async Context Manager

This is an asynchronous version of `contextlib.contextmanager <https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager>`__ to make it easier to write asynchronous context managers without creating boilerplate classes.

import asyncio
import aiotools

@aiotools.actxmgr
async def mygen(a):
    await asyncio.sleep(1)
    yield a + 1
    await asyncio.sleep(1)

async def somewhere():
    async with mygen(1) as b:
        assert b == 2

Note that you need to wrap yield with a try-finally block to ensure resource releases (e.g., locks), even in the case when an exception is ocurred inside the async-with block.

import asyncio
import aiotools

lock = asyncio.Lock()

@aiotools.actxmgr
async def mygen(a):
    await lock.acquire()
    try:
        yield a + 1
    finally:
        lock.release()

async def somewhere():
    try:
        async with mygen(1) as b:
            raise RuntimeError('oops')
    except RuntimeError:
        print('caught!')  # you can catch exceptions here.

You can also create a group of async context managers, which are entered/exited all at once using asyncio.gather.

import asyncio
import aiotools

@aiotools.actxmgr
async def mygen(a):
    yield a + 10

async def somewhere():
    ctxgrp = aiotools.actxgroup(mygen(i) for i in range(10))
    async with ctxgrp as values:
        assert len(values) == 10
        for i in range(10):
            assert values[i] == i + 10

Async Timer

import aiotools

i = 0

async def mytick(interval):
    print(i)
    i += 1

async def somewhere():
    t = aiotools.create_timer(mytick, 1.0)
    ...
    t.cancel()
    await t

t is an `asyncio.Task <https://docs.python.org/3/library/asyncio-task.html#asyncio.Task>`__ object. To stop the timer, call t.cancel(); await t. Please don’t forget await-ing t because it requires extra steps to cancel and await all pending tasks. To make your timer function to be cancellable, add a try-except clause catching asyncio.CancelledError since we use it as a termination signal.

You may add TimerDelayPolicy argument to control the behavior when the timer-fired task takes longer than the timer interval. DEFAULT is to accumulate them and cancel all the remainings at once when the timer is cancelled. CANCEL is to cancel any pending previously fired tasks on every interval.

import asyncio
import aiotools

async def mytick(interval):
    await asyncio.sleep(100)  # cancelled on every next interval.

async def somewhere():
    t = aiotools.create_timer(mytick, 1.0, aiotools.TimerDelayPolicy.CANCEL)
    ...
    t.cancel()
    await t

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

aiotools-0.2.0.tar.gz (4.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aiotools-0.2.0-py3-none-any.whl (6.9 kB view details)

Uploaded Python 3

File details

Details for the file aiotools-0.2.0.tar.gz.

File metadata

  • Download URL: aiotools-0.2.0.tar.gz
  • Upload date:
  • Size: 4.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for aiotools-0.2.0.tar.gz
Algorithm Hash digest
SHA256 c9d15506d2fe8db63028c199a7aad1525a5292ae80703831059888038c65f553
MD5 4c377369b3a2410c5525f6342793466e
BLAKE2b-256 9f1fcae8fb40482585ba734e0af648f74fe01b88c3922d7d97a1f361a8dfcd47

See more details on using hashes here.

File details

Details for the file aiotools-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for aiotools-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 02de9931e4c0878f4b20ca8397abc902d738e84fe22b0a7a41dd2178f069fa94
MD5 31f0a8008dc4f935d0cd9768b814a2f5
BLAKE2b-256 f3a233128b70a5020cfccfd66a89f43fd94dd830ebfd2ff32526168f1ca58f43

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page