Skip to content

Memoize asyncio Python calls with a per-result TTL

License

Notifications You must be signed in to change notification settings

michalc/aiomemoizettl

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

aiomemoizettl CircleCI Test Coverage

Memoize asyncio Python calls with a per-result TTL

Installation

pip install aiomemoizettl

Usage

For a coroutine whose arguments are hashable, you can create a memoized version by passing it to memoize_ttl, along with a function that converts its return value to a TTL.

For example, the below

import asyncio
from aiomemoizettl import memoize_ttl

async def main():
    memoized = memoize_ttl(coro, get_ttl=lambda result: result['ttl'])
    results = await asyncio.gather(*[
        memoized(1),
        memoized(2),
    ])
    await asyncio.sleep(1)

    results = await asyncio.gather(*[
        memoized(1),
        memoized(2),  # Will used the cached value of `coro(2)`
    ])

async def coro(value):
    print('Inside coro', value)
    return {'ttl': value, 'some-other': 'data'}

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

will output

Inside coro 1
Inside coro 2
Inside coro 1

About

Memoize asyncio Python calls with a per-result TTL

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages