Skip to main content

Call asynchronous functions of python 3 asyncio infrastructure from synchronous code

Project description

This package implements two primitives (await and spawn) on top of asyncio infrastructure of Python 3. This two functions allow us to call asynchronous functions from synchronous code.

Installation

pip3 install aioawait

Example

from asyncio.tasks import coroutine, sleep, async
from aioawait import await, spawn

@coroutine
def monitor(name, size, total):
    while True:
        print('\ttotal', name, total)
        yield from sleep(1)

@coroutine
def counter(name, size, total):
    """sums into total all numbers from 0 to size"""
    m = async(monitor(name, size, total))

    # monitor could be called using spawn. eg:
    # m = spawn(monitor(name, size, total))

    for n in range(size):
        total[0] += n
        if n % 5 == 0:
            print('sleeping', name, n)
            yield from sleep(2)
        else:
            print('counting', name, n)
            yield

    # stops monitor
    m.cancel()

    return name, 'done', n, total

class Counter:
    """note that this class has no asynchronous code"""

    def __init__(self):
        self.cb = spawn(counter('b', 40, [0]))

    @property
    def counter_a(self):
        return await(counter('a', 20, [0]))

    @property
    def counter_b(self):
        return await(self.cb)

if __name__ == '__main__':
    c = Counter()
    print(c.counter_a)
    print(c.counter_b)

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

aioawait-5.tar.gz (2.8 kB view details)

Uploaded Source

File details

Details for the file aioawait-5.tar.gz.

File metadata

  • Download URL: aioawait-5.tar.gz
  • Upload date:
  • Size: 2.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for aioawait-5.tar.gz
Algorithm Hash digest
SHA256 624e596a506124a98c0a6f6c04f9a61f087066fd0f49d0ea8af2ab33d28ee531
MD5 87d348d3e0be8cab92389916bde86f74
BLAKE2b-256 594d75f7d6eff219cabb2e62688917c90cc0caad952f7cf87cbd44fa1e121046

See more details on using hashes here.

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