Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Simple LRU cache for asyncio

License

NotificationsYou must be signed in to change notification settings

aio-libs/async-lru

Repository files navigation

info:Simple lru cache for asyncio
GitHub Actions CI/CD workflows statusasync-lru @ PyPIMatrix Room — #aio-libs:matrix.orgMatrix Space — #aio-libs-space:matrix.org

Installation

pip install async-lru

Usage

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 allawaits 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.

Thanks

The library was donated byOcean S.A.

Thanks to the company for contribution.


[8]ページ先頭

©2009-2025 Movatter.jp