Skip to main content

Timeout context manager for asyncio Python

Project description

aiotimeout CircleCI Test Coverage

Timeout context manager for asyncio Python

Usage

from aiotimeout import timeout

# Will raise an asyncio.TimeoutError
with timeout(1):
    await asyncio.sleep(1.5)

# Will not raise anything
with timeout(1):
    await asyncio.sleep(0.5)

You can respond to a timeout from outside the context by catching asyncio.TimeoutError

try:
    with timeout(1):
        await asyncio.sleep(1.5)
        print('This line is not reached')
except asyncio.TimeoutError:
    print('Timed out')

or you can respond to a timeout from inside the context by catching asyncio.CancelledError and re-raising.

try:
    with timeout(1):
        try:
            await asyncio.sleep(1.5)
        except asyncio.CancelledError
            print('Doing some cleanup')
            raise
except asyncio.TimeoutError:
    print('Timed out')

Differences to alternatives

  • asyncio.wait_for does not offer a context manager. In some cases a context manager is clearer.

  • asyncio.wait_for creates/uses an extra task. In some cases this is not necessary, and an extra task adds non-determinism in terms of sequence of operations.

  • Clearer internal code [in the author's opinion]. Rather than a custom class, contextlib.contextmanager is used.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aiotimeout-0.0.4.tar.gz (2.0 kB view hashes)

Uploaded Source

Built Distribution

aiotimeout-0.0.4-py3-none-any.whl (3.1 kB view hashes)

Uploaded Python 3

Supported by

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