Skip to main content

Python utils and decorators for cаching with TTL, maxsize and file-based storage.

Project description

Status

WORK IN PROGRESS

Caching

Build Status Coverage Status Python Versions

Python utils and decorators for cаching with TTL, maxsize and file-based storage.

Installation

pip install caching

Usage

from caching import Cache

# File-based cache with unlimited ttl and maximum of 128 cached results
@Cache(ttl=-1, maxsize=128, filepath='/tmp/mycache')
def long_running_function(a, b, *args, c=None, **kwargs):
    pass

# Memory-based cache with limited ttl and maxsize and "least recently used"
# cache replacement policy.
@Cache(ttl=60, maxsize=128, policy='LRU')
def long_running_function(a, b, *args, c=None, **kwargs):
    pass

Advanced usage

from caching import Cache

# One cache for many functions

cache = Cache(filepath='/tmp/mycache', ttl=3600, maxsize=1024)

@cache
def pow(x, y):
    return x**y

@cache
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n-1)


# Caching the last result and returning it only in case of errors

@Cache(maxsize=1, only_on_errors=(ConnectionError, TimeoutError))
def api_request():
    """Request some remote resource which sometimes become unavailable.
    If this functions raises ConnectionError or TimeoutError, then the
    last cached result will be returned, if available."""


# Custom cache key function

@Cache(key=lambda x: x[0])
def toupper(a):
    global call_count
    call_count += 1
    return str(a).upper()

call_count = 0

# The key function returns the same result for both 'aaa' and 'azz'
# so the cached result from the first call is returned in the second call
assert toupper('aaa') == toupper('azz') == 'AAA'
assert call_count == 1


# Using cache as a key-value store

cache = Cache()

try:
    result = cache[1]
except KeyError:
    result = calculate_result(1)
    cache[1] = result
    assert 1 in cache
    assert cache[1] == result
    assert cache.get(1, None) == result
    assert cache.get(2, None) is None

# Cleanup

import os

cache = Cache(filepath='/tmp/mycache')
cache[1] = 'one'
assert 1 in cache
cache.clear()  # empty the cache
assert 1 not in cache
assert list(cache.items()) == []
assert os.path.isfile('/tmp/mycache')
cache.remove()  # Empty the cache and remove the underlying file
assert not os.path.isfile('/tmp/mycache')

Features

  • [x] Memory and file based cache.

  • [x] TTL and maxsize.

  • [x] Works with *args, **kwargs.

  • [x] Works with mutable function arguments of the following types: dict, list, set.

  • [x] FIFO, LRU and LFU cache replacement policies.

  • [x] Customizable cache key function.

  • [ ] Multiprocessing- and thread-safe.

  • [ ] Pluggable external caching backends (see Redis example).

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

caching-0.1.dev8.tar.gz (7.0 kB view details)

Uploaded Source

Built Distribution

caching-0.1.dev8-py2.py3-none-any.whl (8.9 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file caching-0.1.dev8.tar.gz.

File metadata

  • Download URL: caching-0.1.dev8.tar.gz
  • Upload date:
  • Size: 7.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for caching-0.1.dev8.tar.gz
Algorithm Hash digest
SHA256 c9622fa163965cfaf770380271c870be3d62c452de0b8fd654c2b456d81e836f
MD5 277895cb5583474c20a51f3052c2e209
BLAKE2b-256 c67a322066773e60e11e0f2e132530f8a854b786e3efa679eea03dfb7a7ac372

See more details on using hashes here.

File details

Details for the file caching-0.1.dev8-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for caching-0.1.dev8-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 eb64221cdf8de7379b8b8b0f1a7b345e8ece0d16962108eb08e266e2091353d8
MD5 255c6feba773b82776b61d486fb9180d
BLAKE2b-256 a5bf12d4d013aa511b7ce4d31a937604d1028c6116f40fdf6d0522286fa5787c

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page