Skip to content

Latest commit

 

History

History
75 lines (53 loc) · 1.51 KB

README.md

File metadata and controls

75 lines (53 loc) · 1.51 KB

Agent: Async generators for humans

agent provides a simple decorator to create python 3.5 asynchronous iterators via yields

Examples

Make people wait for things for no reason!

import agent
import asyncio

@agent.gen  # Shorthand decorator
def wait_for_me():
  yield 'Like '
  yield from asyncio.sleep(1)
  yield 'the line '
  yield from asyncio.sleep(10)
  yield 'at '
  yield from asyncio.sleep(100)
  yield 'the DMV'

async for part in wait_for_me():
  print(part)

Paginate websites in an easy asynchronous manner.

import agent
import aiohttp

@agent.async_generator
def gen():
  page, url = 0, 'http://example.com/paginated/endpoint'
  while True:
    resp = yield from aiohttp.request('GET', url, params={'page': page})
    resp_json = (yield from resp.json())['data']
    if not resp_json:
      break
    for blob in resp_json['data']:
      yield blob
    page += 1

# Later on....

async for blob in gen():
    # Do work

The possibilities are endless!

For additional, crazier, examples take a look in the tests directory.

Get it

$ pip install -U agent

Caveats

yield from syntax must be used as yield in an async def block is a syntax error.

async def generator():
  yield 1  # Syntax Error :(

asyncio.Futures can not be yielded directly, they must be wrapped by agent.Result.

License

MIT licensed. See the bundled LICENSE file for more details.