- Notifications
You must be signed in to change notification settings - Fork59
Simple LRU cache for asyncio
License
NotificationsYou must be signed in to change notification settings
aio-libs/async-lru
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
info: | Simple lru cache for asyncio |
---|
pip install async-lru
This package is a port of Python's built-infunctools.lru_cache function forasyncio. To better handle async behaviour, it also ensures multiple concurrent calls will only result in 1 call to the wrapped function, with allawait
s receiving the result of that call when it completes.
importasyncioimportaiohttpfromasync_lruimportalru_cache@alru_cache(maxsize=32)asyncdefget_pep(num):resource='http://www.python.org/dev/peps/pep-%04d/'%numasyncwithaiohttp.ClientSession()assession:try:asyncwithsession.get(resource)ass:returnawaits.read()exceptaiohttp.ClientError:return'Not Found'asyncdefmain():fornin8,290,308,320,8,218,320,279,289,320,9991:pep=awaitget_pep(n)print(n,len(pep))print(get_pep.cache_info())# CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)# closing is optional, but highly recommendedawaitget_pep.cache_close()asyncio.run(main())
TTL (time-to-live in seconds, expiration on timeout) is supported by accepting ttl configurationparameter (off by default):
@alru_cache(ttl=5)asyncdeffunc(arg):returnarg*2
The library supports explicit invalidation for specific function call bycache_invalidate():
@alru_cache(ttl=5)asyncdeffunc(arg1,arg2):returnarg1+arg2func.cache_invalidate(1,arg2=2)
The method returns True if corresponding arguments set was cached already, Falseotherwise.
The library was donated byOcean S.A.
Thanks to the company for contribution.
About
Simple LRU cache for asyncio