persistent-cache-decorator


Namepersistent-cache-decorator JSON
Version 0.1.9 PyPI version JSON
download
home_pageNone
SummaryA decorator for caching functions that provides persistence to JSON, pickle, or SQLite
upload_time2024-11-29 21:40:24
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseMIT
keywords json sqlite cache decorator persistence pickle
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # persistent-cache-decorator

[![PyPI - Version](https://img.shields.io/pypi/v/persistent-cache-decorator.svg)](https://pypi.org/project/persistent-cache-decorator)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/persistent-cache-decorator.svg)](https://pypi.org/project/persistent-cache-decorator)
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/FlavioAmurrioCS/persistent-cache-decorator/main.svg)](https://results.pre-commit.ci/latest/github/FlavioAmurrioCS/persistent-cache-decorator/main)

-----

**Table of Contents**

- [persistent-cache-decorator](#persistent-cache-decorator)
  - [Installation](#installation)
  - [Usage](#usage)
  - [Cached Property](#cached-property)
  - [Creating a custom cache backend](#creating-a-custom-cache-backend)
  - [License](#license)

## Installation

```console
pip install persistent-cache-decorator
```

## Usage
```python
from __future__ import annotations

import time

from persistent_cache.backend import CacheBackend
from persistent_cache.decorators import json_cache
from persistent_cache.decorators import persistent_cache


@persistent_cache(minutes=4)
def long_func(n: int) -> str:
    """Long Func Documentation."""
    # Long function
    time.sleep(n)
    return f"{n}"


# reveal_type(long_func)
# Runtime type is "_persistent_cache"
# <persistent_cache_decorator._persistent_cache object at 0x10468be50>

# Call function(takes 5 seconds)
long_func(5)
"5"
# Call function again (takes 0 seconds)
long_func(5)
"5"

# Bypass caching(takes 5 seconds)
long_func.no_cache_call(5)
"5"

# Call function again (takes 0 seconds)
long_func(5)
"5"
# Clear cache for this function
long_func.cache_clear()

# Call function(takes 5 seconds)
long_func(5)
```

## Cached Property
```python
from typing import NamedTuple  # noqa: E402
from persistent_cache.decorators import json_cached_property  # noqa: E402


# To cache instance methods, use the json_cache decorator you can do the following:
# Reference: https://www.youtube.com/watch?v=sVjtp6tGo0g
class Pet:
    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age
        # creating the cache function this way will allow the cache to be cleared using the instance
        # It will also only use the arguments as the key
        self.online_information = json_cache(days=2)(self._online_information)

    def _online_information(self, source: str) -> int:
        # Something that takes a long time
        return len(source)


pet = Pet("Rex", 5)
pet.online_information(source="https://api.github.com/users/rex")
pet.online_information.cache_clear()


# NEW: or you can use the json_cached_property decorator to cache the result of a method
# This makes use of Python's Descriptors: https://www.youtube.com/watch?v=vBys0SwYvCQ
class Person(NamedTuple):
    name: str
    age: int

    # The decorator works with Namedtuples as well as with classes
    @json_cached_property(days=2)
    def online_information(self, source: str) -> int:
        # Something that takes a long time
        return len(source)


person = Person("John", 30)

# The following call will cache the result using the class instance as well as the arguments as the key  # noqa: E501
person.online_information(source="https://api.github.com/users/john")

# To clear the cache, use the method from the class directly
Person.online_information.cache_clear()
```

## Creating a custom cache backend

```python
from typing_extensions import Any  # noqa: E402
from typing import Callable  # noqa: E402
from persistent_cache.decorators import cache_decorator_factory  # noqa: E402
from typing import TYPE_CHECKING  # noqa: E402

if TYPE_CHECKING:
    import datetime
    from persistent_cache.decorators import _R


# Define a custom cache backend
class RedisCacheBackend(CacheBackend):
    def get_cache_or_call(  # type: ignore[empty-body]
        self,
        *,
        func: Callable[..., _R],
        args: tuple[Any, ...],
        kwargs: dict[str, Any],
        lifespan: datetime.timedelta,
    ) -> _R:
        ...

    def del_func_cache(self, *, func: Callable[..., Any]) -> None:
        ...


# Singleton Instance
REDIS_CACHE_BACKEND = RedisCacheBackend()

# Quick way of defining a decorator. You can use this if you want multiple decorators with different cache durations.  # noqa: E501
redis_cache = cache_decorator_factory(backend=REDIS_CACHE_BACKEND)


@redis_cache(days=1)
def foo(time: float) -> float:
    from time import sleep

    sleep(time)
    return time
```

## License

`persistent-cache-decorator` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "persistent-cache-decorator",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "JSON, SQLite, cache, decorator, persistence, pickle",
    "author": null,
    "author_email": "Flavio Amurrio <25621374+FlavioAmurrioCS@users.noreply.github.com>",
    "download_url": "https://files.pythonhosted.org/packages/27/91/026a808003f0c739bf64908a7324191e3e743f764005fa075ce293d5ca65/persistent_cache_decorator-0.1.9.tar.gz",
    "platform": null,
    "description": "# persistent-cache-decorator\n\n[![PyPI - Version](https://img.shields.io/pypi/v/persistent-cache-decorator.svg)](https://pypi.org/project/persistent-cache-decorator)\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/persistent-cache-decorator.svg)](https://pypi.org/project/persistent-cache-decorator)\n[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/FlavioAmurrioCS/persistent-cache-decorator/main.svg)](https://results.pre-commit.ci/latest/github/FlavioAmurrioCS/persistent-cache-decorator/main)\n\n-----\n\n**Table of Contents**\n\n- [persistent-cache-decorator](#persistent-cache-decorator)\n  - [Installation](#installation)\n  - [Usage](#usage)\n  - [Cached Property](#cached-property)\n  - [Creating a custom cache backend](#creating-a-custom-cache-backend)\n  - [License](#license)\n\n## Installation\n\n```console\npip install persistent-cache-decorator\n```\n\n## Usage\n```python\nfrom __future__ import annotations\n\nimport time\n\nfrom persistent_cache.backend import CacheBackend\nfrom persistent_cache.decorators import json_cache\nfrom persistent_cache.decorators import persistent_cache\n\n\n@persistent_cache(minutes=4)\ndef long_func(n: int) -> str:\n    \"\"\"Long Func Documentation.\"\"\"\n    # Long function\n    time.sleep(n)\n    return f\"{n}\"\n\n\n# reveal_type(long_func)\n# Runtime type is \"_persistent_cache\"\n# <persistent_cache_decorator._persistent_cache object at 0x10468be50>\n\n# Call function(takes 5 seconds)\nlong_func(5)\n\"5\"\n# Call function again (takes 0 seconds)\nlong_func(5)\n\"5\"\n\n# Bypass caching(takes 5 seconds)\nlong_func.no_cache_call(5)\n\"5\"\n\n# Call function again (takes 0 seconds)\nlong_func(5)\n\"5\"\n# Clear cache for this function\nlong_func.cache_clear()\n\n# Call function(takes 5 seconds)\nlong_func(5)\n```\n\n## Cached Property\n```python\nfrom typing import NamedTuple  # noqa: E402\nfrom persistent_cache.decorators import json_cached_property  # noqa: E402\n\n\n# To cache instance methods, use the json_cache decorator you can do the following:\n# Reference: https://www.youtube.com/watch?v=sVjtp6tGo0g\nclass Pet:\n    def __init__(self, name: str, age: int) -> None:\n        self.name = name\n        self.age = age\n        # creating the cache function this way will allow the cache to be cleared using the instance\n        # It will also only use the arguments as the key\n        self.online_information = json_cache(days=2)(self._online_information)\n\n    def _online_information(self, source: str) -> int:\n        # Something that takes a long time\n        return len(source)\n\n\npet = Pet(\"Rex\", 5)\npet.online_information(source=\"https://api.github.com/users/rex\")\npet.online_information.cache_clear()\n\n\n# NEW: or you can use the json_cached_property decorator to cache the result of a method\n# This makes use of Python's Descriptors: https://www.youtube.com/watch?v=vBys0SwYvCQ\nclass Person(NamedTuple):\n    name: str\n    age: int\n\n    # The decorator works with Namedtuples as well as with classes\n    @json_cached_property(days=2)\n    def online_information(self, source: str) -> int:\n        # Something that takes a long time\n        return len(source)\n\n\nperson = Person(\"John\", 30)\n\n# The following call will cache the result using the class instance as well as the arguments as the key  # noqa: E501\nperson.online_information(source=\"https://api.github.com/users/john\")\n\n# To clear the cache, use the method from the class directly\nPerson.online_information.cache_clear()\n```\n\n## Creating a custom cache backend\n\n```python\nfrom typing_extensions import Any  # noqa: E402\nfrom typing import Callable  # noqa: E402\nfrom persistent_cache.decorators import cache_decorator_factory  # noqa: E402\nfrom typing import TYPE_CHECKING  # noqa: E402\n\nif TYPE_CHECKING:\n    import datetime\n    from persistent_cache.decorators import _R\n\n\n# Define a custom cache backend\nclass RedisCacheBackend(CacheBackend):\n    def get_cache_or_call(  # type: ignore[empty-body]\n        self,\n        *,\n        func: Callable[..., _R],\n        args: tuple[Any, ...],\n        kwargs: dict[str, Any],\n        lifespan: datetime.timedelta,\n    ) -> _R:\n        ...\n\n    def del_func_cache(self, *, func: Callable[..., Any]) -> None:\n        ...\n\n\n# Singleton Instance\nREDIS_CACHE_BACKEND = RedisCacheBackend()\n\n# Quick way of defining a decorator. You can use this if you want multiple decorators with different cache durations.  # noqa: E501\nredis_cache = cache_decorator_factory(backend=REDIS_CACHE_BACKEND)\n\n\n@redis_cache(days=1)\ndef foo(time: float) -> float:\n    from time import sleep\n\n    sleep(time)\n    return time\n```\n\n## License\n\n`persistent-cache-decorator` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A decorator for caching functions that provides persistence to JSON, pickle, or SQLite",
    "version": "0.1.9",
    "project_urls": {
        "Documentation": "https://github.com/FlavioAmurrioCS/persistent-cache-decorator#readme",
        "Issues": "https://github.com/FlavioAmurrioCS/persistent-cache-decorator/issues",
        "Source": "https://github.com/FlavioAmurrioCS/persistent-cache-decorator"
    },
    "split_keywords": [
        "json",
        " sqlite",
        " cache",
        " decorator",
        " persistence",
        " pickle"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5a76864273f609e3ea43257cbf30ed2800e88072827cf0a25302ce4da29c89e7",
                "md5": "2bfa5d689b6bac8cf894274d62c92c69",
                "sha256": "5b3536cce1e4008baf4a7a315d27554008703374040a67bec3705b66c3934640"
            },
            "downloads": -1,
            "filename": "persistent_cache_decorator-0.1.9-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2bfa5d689b6bac8cf894274d62c92c69",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 14010,
            "upload_time": "2024-11-29T21:40:11",
            "upload_time_iso_8601": "2024-11-29T21:40:11.691282Z",
            "url": "https://files.pythonhosted.org/packages/5a/76/864273f609e3ea43257cbf30ed2800e88072827cf0a25302ce4da29c89e7/persistent_cache_decorator-0.1.9-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2791026a808003f0c739bf64908a7324191e3e743f764005fa075ce293d5ca65",
                "md5": "d7a005fabbc5ebe9c58e27291428f559",
                "sha256": "ab23e11fdc2eb89f86de4a400e23a2bdc01271a943b10b9a7b5101a9bbecd33d"
            },
            "downloads": -1,
            "filename": "persistent_cache_decorator-0.1.9.tar.gz",
            "has_sig": false,
            "md5_digest": "d7a005fabbc5ebe9c58e27291428f559",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 15806,
            "upload_time": "2024-11-29T21:40:24",
            "upload_time_iso_8601": "2024-11-29T21:40:24.781823Z",
            "url": "https://files.pythonhosted.org/packages/27/91/026a808003f0c739bf64908a7324191e3e743f764005fa075ce293d5ca65/persistent_cache_decorator-0.1.9.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-29 21:40:24",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "FlavioAmurrioCS",
    "github_project": "persistent-cache-decorator#readme",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "persistent-cache-decorator"
}
        
Elapsed time: 0.40916s