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.

Files for aiotimeout, version 0.0.4
Filename, size File type Python version Upload date Hashes
Filename, size aiotimeout-0.0.4-py3-none-any.whl (3.1 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size aiotimeout-0.0.4.tar.gz (2.0 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page