{"id":28480049,"url":"https://github.com/dreamlab/memoize","last_synced_at":"2025-07-03T18:31:02.851Z","repository":{"id":38224038,"uuid":"189951273","full_name":"DreamLab/memoize","owner":"DreamLab","description":"Caching library for asynchronous Python applications.","archived":false,"fork":false,"pushed_at":"2024-10-07T08:51:15.000Z","size":176,"stargazers_count":74,"open_issues_count":1,"forks_count":6,"subscribers_count":11,"default_branch":"master","last_synced_at":"2025-06-07T18:47:43.791Z","etag":null,"topics":["asyncio","cache","python","tornado"],"latest_commit_sha":null,"homepage":"https://memoize.readthedocs.io","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DreamLab.png","metadata":{"files":{"readme":"README.rst","changelog":"CHANGELOG.rst","contributing":"docs/contributing.rst","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-06-03T06:55:48.000Z","updated_at":"2025-05-03T20:14:41.000Z","dependencies_parsed_at":"2024-05-06T11:59:12.069Z","dependency_job_id":"a38959e0-e23d-41be-8a98-c2f0f8e254e2","html_url":"https://github.com/DreamLab/memoize","commit_stats":{"total_commits":27,"total_committers":6,"mean_commits":4.5,"dds":0.6296296296296297,"last_synced_commit":"34687bb00ad920699a5f0d676d99d102dc7bd91d"},"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"purl":"pkg:github/DreamLab/memoize","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DreamLab%2Fmemoize","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DreamLab%2Fmemoize/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DreamLab%2Fmemoize/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DreamLab%2Fmemoize/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DreamLab","download_url":"https://codeload.github.com/DreamLab/memoize/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DreamLab%2Fmemoize/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263378988,"owners_count":23457784,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asyncio","cache","python","tornado"],"created_at":"2025-06-07T18:34:05.652Z","updated_at":"2025-07-03T18:31:02.836Z","avatar_url":"https://github.com/DreamLab.png","language":"Python","readme":".. image:: https://img.shields.io/pypi/v/py-memoize.svg\n    :target: https://pypi.org/project/py-memoize\n\n.. image:: https://img.shields.io/pypi/pyversions/py-memoize.svg\n    :target: https://pypi.org/project/py-memoize\n\n.. image:: https://readthedocs.org/projects/memoize/badge/?version=latest\n    :target: https://memoize.readthedocs.io/en/latest/?badge=latest\n\n.. image:: https://github.com/DreamLab/memoize/actions/workflows/tox-tests.yml/badge.svg\n    :target: https://github.com/DreamLab/memoize/actions/workflows/tox-tests.yml\n\n.. image:: https://github.com/DreamLab/memoize/actions/workflows/non-test-tox.yml/badge.svg\n    :target: https://github.com/DreamLab/memoize/actions/workflows/non-test-tox.yml\n\nExtended docs (including API docs) available at `memoize.readthedocs.io \u003chttps://memoize.readthedocs.io\u003e`_.\n\nWhat \u0026 Why\n==========\n\n**What:** Caching library for asyncio Python applications.\n\n**Why:** Python deserves library that works in async world\n(for instance handles `dog-piling \u003chttps://en.wikipedia.org/wiki/Cache_stampede\u003e`_ )\nand has a proper, extensible API.\n\nEtymology\n=========\n\n*In computing, memoization or memoisation is an optimization technique\nused primarily to speed up computer programs by storing the results of\nexpensive function calls and returning the cached result when the same\ninputs occur again. (…) The term “memoization” was coined by Donald\nMichie in 1968 and is derived from the Latin word “memorandum” (“to be\nremembered”), usually truncated as “memo” in the English language, and\nthus carries the meaning of “turning [the results of] a function into\nsomething to be remembered.”*\n~ `Wikipedia \u003chttps://en.wikipedia.org/wiki/Memoization\u003e`_\n\nGetting Started\n===============\n\nInstallation\n------------\n\nBasic Installation\n~~~~~~~~~~~~~~~~~~\n\nTo get you up \u0026 running all you need is to install:\n\n.. code-block:: bash\n\n   pip install py-memoize\n\nInstallation of Extras\n~~~~~~~~~~~~~~~~~~~~~~\n\nTo harness the power of `ujson \u003chttps://pypi.org/project/ujson/\u003e`_ (if JSON SerDe is used) install extra:\n\n.. code-block:: bash\n\n   pip install py-memoize[ujson]\n\nUsage\n-----\n\nProvided examples use default configuration to cache results in memory.\nFor configuration options see `Configurability`_.\n\nasyncio\n~~~~~~~\n\nTo apply default caching configuration use:\n\n..\n    _example_source: examples/basic/basic.py\n\n.. code-block:: python\n\n    import asyncio\n    import random\n    from memoize.wrapper import memoize\n\n\n    @memoize()\n    async def expensive_computation():\n        return 'expensive-computation-' + str(random.randint(1, 100))\n\n\n    async def main():\n        print(await expensive_computation())\n        print(await expensive_computation())\n        print(await expensive_computation())\n\n\n    if __name__ == \"__main__\":\n        asyncio.get_event_loop().run_until_complete(main())\n\n\nFeatures\n========\n\nAsync-first\n-----------\n\nAsynchronous programming is often seen as a huge performance boost in python programming.\nBut with all the benefits it brings there are also new concurrency-related caveats\nlike `dog-piling \u003chttps://en.wikipedia.org/wiki/Cache_stampede\u003e`_.\n\nThis library is built async-oriented from the ground-up, what manifests in, for example,\nin `Dog-piling proofness`_ or `Async cache storage`_.\n\n\nConfigurability\n---------------\n\nWith *memoize* you have under control:\n\n* timeout applied to the cached method;\n* key generation strategy (see :class:`memoize.key.KeyExtractor`);\n  already provided strategies use arguments (both positional \u0026 keyword) and method name (or reference);\n* storage for cached entries/items (see :class:`memoize.storage.CacheStorage`);\n  in-memory storage is already provided;\n  for convenience of implementing new storage adapters some SerDe (:class:`memoize.serde.SerDe`) are provided;\n* eviction strategy (see :class:`memoize.eviction.EvictionStrategy`);\n  least-recently-updated strategy is already provided;\n* entry builder (see :class:`memoize.entrybuilder.CacheEntryBuilder`)\n  which has control over ``update_after``  \u0026 ``expires_after`` described in `Tunable eviction \u0026 async refreshing`_\n* value post-processing (see :class:`memoize.postprocessing.Postprocessing`);\n  noop is the default one;\n  deep-copy post-processing is also provided (be wary of deep-copy cost \u0026 limitations,\n  but deep-copying allows callers to safely modify values retrieved from an in-memory cache).\n\nAll of these elements are open for extension (you can implement and plug-in your own).\nPlease contribute!\n\nExample how to customize default config (everything gets overridden):\n\n..\n    _example_source: examples/configuration/custom_configuration.py\n\n.. code-block:: python\n\n    from datetime import timedelta\n\n    from memoize.configuration import MutableCacheConfiguration, DefaultInMemoryCacheConfiguration\n    from memoize.entrybuilder import ProvidedLifeSpanCacheEntryBuilder\n    from memoize.eviction import LeastRecentlyUpdatedEvictionStrategy\n    from memoize.key import EncodedMethodNameAndArgsKeyExtractor\n    from memoize.postprocessing import DeepcopyPostprocessing\n    from memoize.storage import LocalInMemoryCacheStorage\n    from memoize.wrapper import memoize\n\n    @memoize(\n        configuration=MutableCacheConfiguration\n        .initialized_with(DefaultInMemoryCacheConfiguration())\n        .set_method_timeout(value=timedelta(minutes=2))\n        .set_entry_builder(ProvidedLifeSpanCacheEntryBuilder(update_after=timedelta(minutes=2),\n                                                             expire_after=timedelta(minutes=5)))\n        .set_eviction_strategy(LeastRecentlyUpdatedEvictionStrategy(capacity=2048))\n        .set_key_extractor(EncodedMethodNameAndArgsKeyExtractor(skip_first_arg_as_self=False))\n        .set_storage(LocalInMemoryCacheStorage())\n        .set_postprocessing(DeepcopyPostprocessing()),\n        update_statuses=InMemoryLocks(update_lock_timeout=timedelta(minutes=5))\n    )\n    async def cached():\n        return 'dummy'\n\n\nStill, you can use default configuration which:\n\n* sets timeout for underlying method to 2 minutes;\n* uses in-memory storage;\n* uses method instance \u0026 arguments to infer cache key;\n* stores up to 4096 elements in cache and evicts entries according to least recently updated policy;\n* refreshes elements after 10 minutes \u0026 ignores unrefreshed elements after 30 minutes;\n* does not post-process cached values.\n\nIf that satisfies you, just use default config:\n\n..\n    _example_source: examples/configuration/default_configuration.py\n\n.. code-block:: python\n\n    from memoize.configuration import DefaultInMemoryCacheConfiguration\n    from memoize.wrapper import memoize\n\n\n    @memoize(configuration=DefaultInMemoryCacheConfiguration())\n    async def cached():\n        return 'dummy'\n\nAlso, if you want to stick to the building blocks of the default configuration, but need to adjust some basic params:\n\n..\n    _example_source: examples/configuration/default_customized_configuration.py\n\n.. code-block:: python\n\n    from datetime import timedelta\n\n    from memoize.configuration import DefaultInMemoryCacheConfiguration\n    from memoize.wrapper import memoize\n\n\n    @memoize(configuration=DefaultInMemoryCacheConfiguration(capacity=4096, method_timeout=timedelta(minutes=2),\n                                                             update_after=timedelta(minutes=10),\n                                                             expire_after=timedelta(minutes=30)))\n    async def cached():\n        return 'dummy'\n\nTunable eviction \u0026 async refreshing\n-----------------------------------\n\nSometimes caching libraries allow providing TTL only. This may result in a scenario where when the cache entry expires\nlatency is increased as the new value needs to be recomputed.\nTo mitigate this periodic extra latency multiple delays are often used. In the case of *memoize* there are two\n(see :class:`memoize.entrybuilder.ProvidedLifeSpanCacheEntryBuilder`):\n\n* ``update_after`` defines delay after which background/async update is executed;\n* ``expire_after`` defines delay after which entry is considered outdated and invalid.\n\nThis allows refreshing cached value in the background without any observable latency.\nMoreover, if some of those background refreshes fail they will be retried still in the background.\nDue to this beneficial feature, it is recommended to ``update_after`` be significantly shorter than ``expire_after``.\n\nDog-piling proofness\n--------------------\n\nIf some resource is accessed asynchronously `dog-piling \u003chttps://en.wikipedia.org/wiki/Cache_stampede\u003e`_ may occur.\nCaches designed for synchronous python code\n(like built-in `LRU \u003chttps://docs.python.org/3.3/library/functools.html#lru_cache\u003e`_)\nwill allow multiple concurrent tasks to observe a miss for the same resource and will proceed to flood underlying/cached\nbackend with requests for the same resource.\n\n\nAs it breaks the purpose of caching (as backend effectively sometimes is not protected with cache)\n*memoize* has built-in dog-piling protection.\n\nUnder the hood, concurrent requests for the same resource (cache key) get collapsed to a single request to the backend.\nWhen the resource is fetched all requesters obtain the result.\nOn failure, all requesters get an exception (same happens on timeout).\n\nAn example of what it all is about:\n\n..\n    _example_source: examples/dogpiling/dogpiling.py\n\n.. code-block:: python\n\n    import asyncio\n    from datetime import timedelta\n\n    from aiocache import cached, SimpleMemoryCache  # version 0.11.1 (latest) used as example of other cache implementation\n\n    from memoize.configuration import DefaultInMemoryCacheConfiguration\n    from memoize.wrapper import memoize\n\n    # scenario configuration\n    concurrent_requests = 5\n    request_batches_execution_count = 50\n    cached_value_ttl_ms = 200\n    delay_between_request_batches_ms = 70\n\n    # results/statistics\n    unique_calls_under_memoize = 0\n    unique_calls_under_different_cache = 0\n\n\n    @memoize(configuration=DefaultInMemoryCacheConfiguration(update_after=timedelta(milliseconds=cached_value_ttl_ms)))\n    async def cached_with_memoize():\n        global unique_calls_under_memoize\n        unique_calls_under_memoize += 1\n        await asyncio.sleep(0.01)\n        return unique_calls_under_memoize\n\n\n    @cached(ttl=cached_value_ttl_ms / 1000, cache=SimpleMemoryCache)\n    async def cached_with_different_cache():\n        global unique_calls_under_different_cache\n        unique_calls_under_different_cache += 1\n        await asyncio.sleep(0.01)\n        return unique_calls_under_different_cache\n\n\n    async def main():\n        for i in range(request_batches_execution_count):\n            await asyncio.gather(*[x() for x in [cached_with_memoize] * concurrent_requests])\n            await asyncio.gather(*[x() for x in [cached_with_different_cache] * concurrent_requests])\n            await asyncio.sleep(delay_between_request_batches_ms / 1000)\n\n        print(\"Memoize generated {} unique backend calls\".format(unique_calls_under_memoize))\n        print(\"Other cache generated {} unique backend calls\".format(unique_calls_under_different_cache))\n        predicted = (delay_between_request_batches_ms * request_batches_execution_count) // cached_value_ttl_ms\n        print(\"Predicted (according to TTL) {} unique backend calls\".format(predicted))\n\n        # Printed:\n        # Memoize generated 17 unique backend calls\n        # Other cache generated 85 unique backend calls\n        # Predicted (according to TTL) 17 unique backend calls\n\n    if __name__ == \"__main__\":\n        asyncio.get_event_loop().run_until_complete(main())\n\n\nAsync cache storage\n-------------------\n\nInterface for cache storage allows you to fully harness benefits of asynchronous programming\n(see interface of :class:`memoize.storage.CacheStorage`).\n\n\nCurrently *memoize* provides only in-memory storage for cache values (internally at *RASP* we have others).\nIf you want (for instance) Redis integration, you need to implement one (please contribute!)\nbut *memoize* will optimally use your async implementation from the start.\n\nManual Invalidation\n-------------------\n\nYou could also invalidate entries manually.\nTo do so you need to create instance of :class:`memoize.invalidation.InvalidationSupport`)\nand pass it alongside cache configuration.\nThen you could just pass args and kwargs for which you want to invalidate entry.\n\n..\n    _example_source: memoize/invalidation.py\n\n.. code-block:: python\n\n    from memoize.configuration import DefaultInMemoryCacheConfiguration\n    from memoize.invalidation import InvalidationSupport\n\n\n    import asyncio\n    import random\n    from memoize.wrapper import memoize\n\n    invalidation = InvalidationSupport()\n\n\n    @memoize(configuration=DefaultInMemoryCacheConfiguration(), invalidation=invalidation)\n    async def expensive_computation(*args, **kwargs):\n        return 'expensive-computation-' + str(random.randint(1, 100))\n\n\n    async def main():\n        print(await expensive_computation('arg1', kwarg='kwarg1'))\n        print(await expensive_computation('arg1', kwarg='kwarg1'))\n\n        print(\"Invalidation #1\")\n        await invalidation.invalidate_for_arguments(('arg1',), {'kwarg': 'kwarg1'})\n\n        print(await expensive_computation('arg1', kwarg='kwarg1'))\n        print(await expensive_computation('arg1', kwarg='kwarg1'))\n\n        print(\"Invalidation #2\")\n        await invalidation.invalidate_for_arguments(('arg1',), {'kwarg': 'kwarg1'})\n\n        print(await expensive_computation('arg1', kwarg='kwarg1'))\n\n        # Sample output:\n        #\n        # expensive - computation - 98\n        # expensive - computation - 98\n        # Invalidation  # 1\n        # expensive - computation - 73\n        # expensive - computation - 73\n        # Invalidation  # 2\n        # expensive - computation - 59\n\n    if __name__ == \"__main__\":\n        asyncio.get_event_loop().run_until_complete(main())\n\n\nOpenness to granular TTL\n------------------------\n\nDefault configuration sets update and expiry based on fixed values, which are the same for all entries.\nIf you need to set different TTLs for different entries, you can do so by providing\na custom :class:`memoize.entrybuilder.CacheEntryBuilder`.\n\n.. code-block:: python\n\n    import datetime\n    import asyncio\n    import random\n    from dataclasses import dataclass\n\n    from memoize.wrapper import memoize\n    from memoize.configuration import DefaultInMemoryCacheConfiguration, MutableCacheConfiguration\n    from memoize.entry import CacheKey, CacheEntry\n    from memoize.entrybuilder import CacheEntryBuilder\n    from memoize.storage import LocalInMemoryCacheStorage\n\n\n    @dataclass\n    class ValueWithTTL:\n        value: str\n        ttl_seconds: int  # for instance, it could be derived from Cache-Control response header\n\n\n    class TtlRespectingCacheEntryBuilder(CacheEntryBuilder):\n        def build(self, key: CacheKey, value: ValueWithTTL):\n            now = datetime.datetime.now(datetime.timezone.utc)\n            ttl_ends_at = now + datetime.timedelta(seconds=value.ttl_seconds)\n            return CacheEntry(\n                created=now,\n                update_after=ttl_ends_at,\n                # allowing stale data for 10% of TTL\n                expires_after=ttl_ends_at + datetime.timedelta(seconds=value.ttl_seconds // 10),\n                value=value\n            )\n\n\n    storage = LocalInMemoryCacheStorage()  # overridden \u0026 extracted for demonstration purposes only\n\n\n    @memoize(configuration=MutableCacheConfiguration\n             .initialized_with(DefaultInMemoryCacheConfiguration())\n             .set_entry_builder(TtlRespectingCacheEntryBuilder())\n             .set_storage(storage))\n    async def external_call(key: str):\n        return ValueWithTTL(\n            value=f'{key}-result-{random.randint(1, 100)}',\n            ttl_seconds=random.randint(60, 300)\n        )\n\n\n    async def main():\n        await external_call('a')\n        await external_call('b')\n        await external_call('b')\n\n        print(\"Entries persisted in the cache:\")\n        for entry in storage._data.values():\n            print('Entry: ', entry.value)\n            print('Effective TTL: ', (entry.update_after - entry.created).total_seconds())\n\n        # Entries persisted in the cache:\n        # Entry: ValueWithTTL(value='a-result-79', ttl_seconds=148)\n        # Effective TTL: 148.0\n        # Entry: ValueWithTTL(value='b-result-27', ttl_seconds=192)\n        # Effective TTL: 192.0\n\n\n    if __name__ == \"__main__\":\n        asyncio.get_event_loop().run_until_complete(main())","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdreamlab%2Fmemoize","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdreamlab%2Fmemoize","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdreamlab%2Fmemoize/lists"}