parametric-ttl-cache


Nameparametric-ttl-cache JSON
Version 1.0.2 PyPI version JSON
download
home_pagehttps://github.com/jogakdal/python_ttl_cache
SummaryA function-level memory cache that supports Time To Live (TTL)
upload_time2025-01-20 02:17:36
maintainerNone
docs_urlNone
authorYongho Hwang
requires_python>=3.6
licenseNone
keywords cache memory cache ttl cache function cache cache decorator parametric cache jogakdal
VCS
bugtrack_url
requirements backports-tarfile certifi charset-normalizer docutils expiringdict idna importlib-metadata jaraco-classes jaraco-context jaraco-functools keyring markdown-it-py mdurl more-itertools nh3 pkginfo pygments readme-renderer requests requests-toolbelt rfc3986 rich twine urllib3 wheel zipp
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # TTL Cache

A function-level memory cache that supports Time To Live (TTL).

- **Per-function argument caching**: Caching is possible based on the data passed to function arguments. The cache key is composed of the function name, argument names, and the values of the arguments.
- **Automatic expiration**: Cached data expires and is automatically deleted after the specified TTL (in seconds).
- **LRU policy**: When the cache exceeds its maximum size (`max_size`), the Least Recently Used (LRU) policy is applied to delete items.
- **Easy application**: Simply add the `@TtlCache(ttl=seconds)` decorator to the function you want to cache.

## Parameters:

- **ttl**: TTL for the cached data (in seconds).
- **max_size**: Maximum number of cache entries.
- **applying_params**: List of parameter names to use as the cache key. If `None`, all parameters are used. If `[]`, only the function name is used.

## Member Functions:

- **force_expire(key)**: Forces expiration of the cache entry for the specified key.
- **is_exist(key)**: Checks if a specific key exists in the cache.
- **get_item(key)**: Returns the cache item for the specified key.
  - *Note*: The key can include partial elements of the cache key.

## Usage:
1. Install the package using `pip install parametric-ttl-cache`.
2. Import the `TtlCache` class `from parametric_ttl_cache.ttl_cache import TtlCache`.
2. Add the `@TtlCache(ttl=seconds)` decorator to the function you want to cache.
3. Cache keys are generated in the format `"{class_name.}method_name(param1=value1, param2=value2, ...)"`.
4. To call the member functions of `TtlCache`, create an instance of `TtlCache` and use that instance as the decorator.

## Source code installation:
```bash
git clone https://github.com/jogakdal/python_ttl_cache.git
cd python_ttl_cache
pip install -r requirements.txt
```

### Example:
```python
from parametric_ttl_cache.ttl_cache import TtlCache


some_cache = TtlCache(ttl=5)

@some_cache
def some_function(x):
    return x * 2

@TtlCache(ttl=5, max_size=10, applying_params=['key'])
def another_function(key, value):
    return f'{key} = {value}'

# Usage
result = some_function(1)
some_cache.force_expire('some_function(x=1)')
```

### Test:
```python
import unittest
import time

from parametric_ttl_cache.ttl_cache import TtlCache


class TestTtlCache(unittest.TestCase):
    __increment = 0
    def test_ttl_cache(self):
        ttl = 2  # 2 seconds
        cache = TtlCache(ttl)

        def incrementer():
            self.__increment += 1
            return self.__increment

        @cache
        def func(x=1):
            return x + incrementer()

        self.assertEqual(func(1), 2, '첫 번 째 호출은 정상적으로 실행')
        self.assertEqual(func(1), 2, '두 번 째 호출은 캐시에서 가져와야 하고 incrementer가 호출되지 않아야 함')
        self.assertEqual(func(x=1), 2, '명시적인 키워드 인자도 동일한 캐시 키로 사용되어야 함')
        self.assertEqual(func(), 2, '디폴트 인자와 캐시 키로 사용된 인자가 같으면 같은 캐시 키로 취급되어야 함')
        self.assertEqual(func(2), 4, '인자가 다르면 다른 캐시가 생성되어야 함')

        # 캐시 expire
        time.sleep(ttl + 1)

        self.assertEqual(func(1), 4, '캐시가 expire 되었으므로 incrementer가 호출되어야 함')
        self.assertEqual(func(1), 4, '이 전 호출에서 캐시가 다시 생성되어야 함')

        # 캐시 강제 expire
        cache.force_expire('x=1')

        self.assertEqual(func(1), 5, '강제로 캐시를 expire시키면 incrementer가 호출되어야 함')


if __name__ == '__main__':
    unittest.main()
```



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/jogakdal/python_ttl_cache",
    "name": "parametric-ttl-cache",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": null,
    "keywords": "cache, memory cache, ttl cache, function cache, cache decorator, parametric cache, jogakdal",
    "author": "Yongho Hwang",
    "author_email": "jogakdal@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/bb/d6/0424a4bb1adb8b395187273c49e9b65fd3097661211ca3f3c1296b27ceb2/parametric-ttl-cache-1.0.2.tar.gz",
    "platform": null,
    "description": "# TTL Cache\n\nA function-level memory cache that supports Time To Live (TTL).\n\n- **Per-function argument caching**: Caching is possible based on the data passed to function arguments. The cache key is composed of the function name, argument names, and the values of the arguments.\n- **Automatic expiration**: Cached data expires and is automatically deleted after the specified TTL (in seconds).\n- **LRU policy**: When the cache exceeds its maximum size (`max_size`), the Least Recently Used (LRU) policy is applied to delete items.\n- **Easy application**: Simply add the `@TtlCache(ttl=seconds)` decorator to the function you want to cache.\n\n## Parameters:\n\n- **ttl**: TTL for the cached data (in seconds).\n- **max_size**: Maximum number of cache entries.\n- **applying_params**: List of parameter names to use as the cache key. If `None`, all parameters are used. If `[]`, only the function name is used.\n\n## Member Functions:\n\n- **force_expire(key)**: Forces expiration of the cache entry for the specified key.\n- **is_exist(key)**: Checks if a specific key exists in the cache.\n- **get_item(key)**: Returns the cache item for the specified key.\n  - *Note*: The key can include partial elements of the cache key.\n\n## Usage:\n1. Install the package using `pip install parametric-ttl-cache`.\n2. Import the `TtlCache` class `from parametric_ttl_cache.ttl_cache import TtlCache`.\n2. Add the `@TtlCache(ttl=seconds)` decorator to the function you want to cache.\n3. Cache keys are generated in the format `\"{class_name.}method_name(param1=value1, param2=value2, ...)\"`.\n4. To call the member functions of `TtlCache`, create an instance of `TtlCache` and use that instance as the decorator.\n\n## Source code installation:\n```bash\ngit clone https://github.com/jogakdal/python_ttl_cache.git\ncd python_ttl_cache\npip install -r requirements.txt\n```\n\n### Example:\n```python\nfrom parametric_ttl_cache.ttl_cache import TtlCache\n\n\nsome_cache = TtlCache(ttl=5)\n\n@some_cache\ndef some_function(x):\n    return x * 2\n\n@TtlCache(ttl=5, max_size=10, applying_params=['key'])\ndef another_function(key, value):\n    return f'{key} = {value}'\n\n# Usage\nresult = some_function(1)\nsome_cache.force_expire('some_function(x=1)')\n```\n\n### Test:\n```python\nimport unittest\nimport time\n\nfrom parametric_ttl_cache.ttl_cache import TtlCache\n\n\nclass TestTtlCache(unittest.TestCase):\n    __increment = 0\n    def test_ttl_cache(self):\n        ttl = 2  # 2 seconds\n        cache = TtlCache(ttl)\n\n        def incrementer():\n            self.__increment += 1\n            return self.__increment\n\n        @cache\n        def func(x=1):\n            return x + incrementer()\n\n        self.assertEqual(func(1), 2, '\uccab \ubc88 \uc9f8 \ud638\ucd9c\uc740 \uc815\uc0c1\uc801\uc73c\ub85c \uc2e4\ud589')\n        self.assertEqual(func(1), 2, '\ub450 \ubc88 \uc9f8 \ud638\ucd9c\uc740 \uce90\uc2dc\uc5d0\uc11c \uac00\uc838\uc640\uc57c \ud558\uace0 incrementer\uac00 \ud638\ucd9c\ub418\uc9c0 \uc54a\uc544\uc57c \ud568')\n        self.assertEqual(func(x=1), 2, '\uba85\uc2dc\uc801\uc778 \ud0a4\uc6cc\ub4dc \uc778\uc790\ub3c4 \ub3d9\uc77c\ud55c \uce90\uc2dc \ud0a4\ub85c \uc0ac\uc6a9\ub418\uc5b4\uc57c \ud568')\n        self.assertEqual(func(), 2, '\ub514\ud3f4\ud2b8 \uc778\uc790\uc640 \uce90\uc2dc \ud0a4\ub85c \uc0ac\uc6a9\ub41c \uc778\uc790\uac00 \uac19\uc73c\uba74 \uac19\uc740 \uce90\uc2dc \ud0a4\ub85c \ucde8\uae09\ub418\uc5b4\uc57c \ud568')\n        self.assertEqual(func(2), 4, '\uc778\uc790\uac00 \ub2e4\ub974\uba74 \ub2e4\ub978 \uce90\uc2dc\uac00 \uc0dd\uc131\ub418\uc5b4\uc57c \ud568')\n\n        # \uce90\uc2dc expire\n        time.sleep(ttl + 1)\n\n        self.assertEqual(func(1), 4, '\uce90\uc2dc\uac00 expire \ub418\uc5c8\uc73c\ubbc0\ub85c incrementer\uac00 \ud638\ucd9c\ub418\uc5b4\uc57c \ud568')\n        self.assertEqual(func(1), 4, '\uc774 \uc804 \ud638\ucd9c\uc5d0\uc11c \uce90\uc2dc\uac00 \ub2e4\uc2dc \uc0dd\uc131\ub418\uc5b4\uc57c \ud568')\n\n        # \uce90\uc2dc \uac15\uc81c expire\n        cache.force_expire('x=1')\n\n        self.assertEqual(func(1), 5, '\uac15\uc81c\ub85c \uce90\uc2dc\ub97c expire\uc2dc\ud0a4\uba74 incrementer\uac00 \ud638\ucd9c\ub418\uc5b4\uc57c \ud568')\n\n\nif __name__ == '__main__':\n    unittest.main()\n```\n\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A function-level memory cache that supports Time To Live (TTL)",
    "version": "1.0.2",
    "project_urls": {
        "Homepage": "https://github.com/jogakdal/python_ttl_cache"
    },
    "split_keywords": [
        "cache",
        " memory cache",
        " ttl cache",
        " function cache",
        " cache decorator",
        " parametric cache",
        " jogakdal"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7ef685d80dddaf94e30bfaac7e98fed7ed563c30ef0131470a54c661c0cfe2d1",
                "md5": "4a34bf973b33e6750f001146715a445b",
                "sha256": "36ea853b597465387c1622a94aabfd25a84bd858128186a4bbf817a16dde8c97"
            },
            "downloads": -1,
            "filename": "parametric_ttl_cache-1.0.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "4a34bf973b33e6750f001146715a445b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 4803,
            "upload_time": "2025-01-20T02:17:35",
            "upload_time_iso_8601": "2025-01-20T02:17:35.010370Z",
            "url": "https://files.pythonhosted.org/packages/7e/f6/85d80dddaf94e30bfaac7e98fed7ed563c30ef0131470a54c661c0cfe2d1/parametric_ttl_cache-1.0.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "bbd60424a4bb1adb8b395187273c49e9b65fd3097661211ca3f3c1296b27ceb2",
                "md5": "7ff981ea60fb8a3ad99dc9fe88ad99ca",
                "sha256": "a250cc1d9a8f02b99f1c40c55601c3b4b9948d54881a3e121c206cdb3fe86670"
            },
            "downloads": -1,
            "filename": "parametric-ttl-cache-1.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "7ff981ea60fb8a3ad99dc9fe88ad99ca",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 4483,
            "upload_time": "2025-01-20T02:17:36",
            "upload_time_iso_8601": "2025-01-20T02:17:36.559816Z",
            "url": "https://files.pythonhosted.org/packages/bb/d6/0424a4bb1adb8b395187273c49e9b65fd3097661211ca3f3c1296b27ceb2/parametric-ttl-cache-1.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-01-20 02:17:36",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "jogakdal",
    "github_project": "python_ttl_cache",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "backports-tarfile",
            "specs": [
                [
                    "==",
                    "1.2.0"
                ]
            ]
        },
        {
            "name": "certifi",
            "specs": [
                [
                    "==",
                    "2024.6.2"
                ]
            ]
        },
        {
            "name": "charset-normalizer",
            "specs": [
                [
                    "==",
                    "3.3.2"
                ]
            ]
        },
        {
            "name": "docutils",
            "specs": [
                [
                    "==",
                    "0.21.2"
                ]
            ]
        },
        {
            "name": "expiringdict",
            "specs": [
                [
                    "==",
                    "1.2.2"
                ]
            ]
        },
        {
            "name": "idna",
            "specs": [
                [
                    "==",
                    "3.7"
                ]
            ]
        },
        {
            "name": "importlib-metadata",
            "specs": [
                [
                    "==",
                    "7.1.0"
                ]
            ]
        },
        {
            "name": "jaraco-classes",
            "specs": [
                [
                    "==",
                    "3.4.0"
                ]
            ]
        },
        {
            "name": "jaraco-context",
            "specs": [
                [
                    "==",
                    "5.3.0"
                ]
            ]
        },
        {
            "name": "jaraco-functools",
            "specs": [
                [
                    "==",
                    "4.0.1"
                ]
            ]
        },
        {
            "name": "keyring",
            "specs": [
                [
                    "==",
                    "25.2.1"
                ]
            ]
        },
        {
            "name": "markdown-it-py",
            "specs": [
                [
                    "==",
                    "3.0.0"
                ]
            ]
        },
        {
            "name": "mdurl",
            "specs": [
                [
                    "==",
                    "0.1.2"
                ]
            ]
        },
        {
            "name": "more-itertools",
            "specs": [
                [
                    "==",
                    "10.3.0"
                ]
            ]
        },
        {
            "name": "nh3",
            "specs": [
                [
                    "==",
                    "0.2.17"
                ]
            ]
        },
        {
            "name": "pkginfo",
            "specs": [
                [
                    "==",
                    "1.11.1"
                ]
            ]
        },
        {
            "name": "pygments",
            "specs": [
                [
                    "==",
                    "2.18.0"
                ]
            ]
        },
        {
            "name": "readme-renderer",
            "specs": [
                [
                    "==",
                    "43.0"
                ]
            ]
        },
        {
            "name": "requests",
            "specs": [
                [
                    "==",
                    "2.32.3"
                ]
            ]
        },
        {
            "name": "requests-toolbelt",
            "specs": [
                [
                    "==",
                    "1.0.0"
                ]
            ]
        },
        {
            "name": "rfc3986",
            "specs": [
                [
                    "==",
                    "2.0.0"
                ]
            ]
        },
        {
            "name": "rich",
            "specs": [
                [
                    "==",
                    "13.7.1"
                ]
            ]
        },
        {
            "name": "twine",
            "specs": [
                [
                    "==",
                    "5.1.0"
                ]
            ]
        },
        {
            "name": "urllib3",
            "specs": [
                [
                    "==",
                    "2.2.2"
                ]
            ]
        },
        {
            "name": "wheel",
            "specs": [
                [
                    "==",
                    "0.43.0"
                ]
            ]
        },
        {
            "name": "zipp",
            "specs": [
                [
                    "==",
                    "3.19.2"
                ]
            ]
        }
    ],
    "lcname": "parametric-ttl-cache"
}
        
Elapsed time: 0.51121s