Skip to main content

Memoiz is a memoization decorator that makes reasonable assumptions about how and if to cache the return value of a function or method based on the arguments passed to it. The decorator can be used on both free and bound functions.

Project description

Memoiz

A thread-safe memoization decorator for functions and methods.

Introduction

Memoiz is a memoization decorator that makes reasonable assumptions about how and if to cache the return value of a function or method based on the arguments passed to it. The decorator can be used on both free and bound functions.

Features

  • Thread-safe memoization
  • Memoization for free and bound functions
  • Configurable immutables
  • Support for parameter and return type hints
  • Cache invalidation

Table of Contents

Installation

pip install memoiz

Usage

Memoization and Cache Invalidation for Bound Functions

In this example you will use Memoiz to memoize the return value of the greeter.greet method and print the greeting.

from memoiz.cache import Cache

cache = Cache()


class Greeter:

    def __init__(self):
        self.adv = "Very"

    @cache
    def greet(self, adj: str) -> str:
        return f"Hello, {self.adv} {adj} World!"


greeter = Greeter()

print("1:", cache._cache)

greeting = greeter.greet("Happy")

print("2:", greeting)
1: {}
2: Hello, Very Happy World!

As a continuation of the above example, you will selectively invalidate the cache using the cache.invalidate method.

greeter = Greeter()

print("1:", cache._cache)

greeting = greeter.greet("Happy")

print("2:", greeting)

greeting = greeter.greet("Cautious")

print("3:", greeting)

# The cache has memoized the call using the `Happy` argument and the call using the `Cautious` argument.
print("4:", cache._cache)

# Invalidate the call to `greeter.greet` with the `Happy` argument. Provide a reference to the method, the object, and the argument.
cache.invalidate(greeter.greet, greeter, "Happy")

print("5:", cache._cache)

# Invalidate the call to `greeter.greet` with the `Cautious` argument.
cache.invalidate(greeter.greet, greeter, "Cautious")

# The cache is empty.
print("6:", cache._cache)
1: {}
2: Hello, Very Happy World!
3: Hello, Very Cautious World!
4: {<bound method Greeter.greet of <__main__.Greeter object at 0x7fa5e7f837f0>>: {((<__main__.Greeter object at 0x7fa5e7f837f0>, 'Happy'), ()): 'Hello, Very Happy World!', ((<__main__.Greeter object at 0x7fa5e7f837f0>, 'Cautious'), ()): 'Hello, Very Cautious World!'}}
5: {<bound method Greeter.greet of <__main__.Greeter object at 0x7fa5e7f837f0>>: {((<__main__.Greeter object at 0x7fa5e7f837f0>, 'Cautious'), ()): 'Hello, Very Cautious World!'}}
6: {}

Memoization and Cache Invalidation for Free Functions

In this example you will use Memoiz to memoize the return value of the greet function and print the greeting.

from memoiz.cache import Cache

cache = Cache()


@cache
def greet(adj: str) -> str:
    return f"Hello, {adj} World!"


print("1:", cache._cache)

greeting = greet("Happy")

print("2:", greeting)
1: {}
2: Hello, Happy World!

As a continuation of the above example, you will selectively invalidate the cache using the cache.invalidate method.

print("1:", cache._cache)

greeting = greet("Happy")

print("2:", greeting)

greeting = greet("Cautious")

print("3:", greeting)

print("4:", cache._cache)

cache.invalidate(greet, "Happy")

print("5:", cache._cache)

cache.invalidate(greet, "Cautious")

print("6:", cache._cache)
1: {}
2: Hello, Happy World!
3: Hello, Cautious World!
4: {<function greet at 0x7fa5cefb8430>: {(('Happy',), ()): 'Hello, Happy World!', (('Cautious',), ()): 'Hello, Cautious World!'}}
5: {<function greet at 0x7fa5cefb8430>: {(('Cautious',), ()): 'Hello, Cautious World!'}}
6: {}

API

The Cache Class

memoiz.Cache(immutables, allow_hash, deep_copy)

  • immutables Tuple[type, ...] An optional list of objects that are assumed to be immutable. Default: (int, float, complex, bool, str, type(None))
  • allow_hash bool An optional flag that indicates if an object's hash is sufficient for indexing the callable's arguments. Default: True
  • deep_copy bool Optionally return the cached return value using Python's copy.deepcopy. This can help prevent mutations of the cached return value. Default: True.

cache.call(callable)

  • callable typing.Callable The function or method to be memoized.

The Cache instance is a callable. This is the @cache decorator that is used in order to memoize a function or method. Please see the above usage for how to use this decorator.

**cache.invalidate(callable, *args, **kwargs)**

  • callable typing.Callable The memoized callable.
  • args Any The arguments passed to the callable.
  • kwargs Any The keyword arguments passed to the callable.

Invalidates the cache for the specified callable and arguments. See the usage for for how to invalidate the cache.

NB The first argument of a method (i.e., a bound function) is the object instance e.g., the self.

cache.invalidate_all()

Resets the cache making the old cache eligible for garbage collection.

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

memoiz-1.0.0.tar.gz (6.3 kB view details)

Uploaded Source

Built Distribution

memoiz-1.0.0-py3-none-any.whl (5.2 kB view details)

Uploaded Python 3

File details

Details for the file memoiz-1.0.0.tar.gz.

File metadata

  • Download URL: memoiz-1.0.0.tar.gz
  • Upload date:
  • Size: 6.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-httpx/0.27.2

File hashes

Hashes for memoiz-1.0.0.tar.gz
Algorithm Hash digest
SHA256 82c537eb042e87fe9f56f13a4ca9564a60d8f91958bb4d94b079a300f2283b5e
MD5 1a6442ab74380713469c491c047c9924
BLAKE2b-256 4cdf5dfff807d2d9729274911c89dc93fad7ff3ba40eca5eaef1b5136dac6e1a

See more details on using hashes here.

File details

Details for the file memoiz-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: memoiz-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 5.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-httpx/0.27.2

File hashes

Hashes for memoiz-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0982abb8be54d975110cdaf4f6def5d397163e3ec47da0be8d613ebacb596385
MD5 277ce33cd423b27ad128c609d32a0dc0
BLAKE2b-256 84434554ed0d7986fd4cb7749b0b11f875f408bd2440e5019e63aa3f622badb4

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