Skip to main content

Per-instance memoization for class methods with full type hint preservation

Project description

GeoSol Research Logo

Memoize (Class-Based Memoization)

Per-instance memoization for class methods with full type hint and docstring preservation.

Overview

gri-memoize provides a MemoizedClass base class and a @memoize decorator for caching method results within class instances. Unlike functools.lru_cache, which stores results in a global cache tied to the function object, gri-memoize keeps cached results on each instance -- so garbage collection, per-instance invalidation, and IDE tooling all work as expected.

Requires Python 3.12+.

Installation

pip install gri-memoize

For development:

git clone https://gitlab.com/geosol-foss/python/gri-memoize.git
cd gri-memoize
uv sync

Quick Start

from gri_memoize import MemoizedClass, memoize


class Geometry(MemoizedClass):
    def __init__(self, radius: float):
        self._radius = radius

    @memoize
    def area(self) -> float:
        """Circle area (cached after first call)."""
        return 3.14159 * self._radius ** 2

    @memoize
    def circumference(self) -> float:
        """Circle circumference (cached after first call)."""
        return 2 * 3.14159 * self._radius


g = Geometry(5.0)
g.area()           # Computed
g.area()           # Returned from cache
g.clear_memoized_results()  # Invalidate all cached results
g.area()           # Recomputed

Why Not functools.lru_cache?

Feature lru_cache gri-memoize
Cache scope Global (per function) Per instance
Garbage collection Cache holds references, preventing GC Cache dies with instance
Cache invalidation cache_clear() clears all instances clear_memoized_results() per instance
IDE support Often loses docstrings and type hints in class context Full @wraps preservation
Argument hashing Uses __hash__ on all args Same, plus function name isolation

Usage

  1. Inherit from MemoizedClass
  2. Decorate methods with @memoize
  3. Call clear_memoized_results() if the underlying data changes
from gri_memoize import MemoizedClass, memoize


class Sensor(MemoizedClass):
    def __init__(self, readings: list[float]):
        self._readings = readings

    @memoize
    def mean(self) -> float:
        return sum(self._readings) / len(self._readings)

    @memoize
    def variance(self) -> float:
        m = self.mean()
        return sum((x - m) ** 2 for x in self._readings) / len(self._readings)

    def update(self, readings: list[float]) -> None:
        self._readings = readings
        self.clear_memoized_results()  # Invalidate stale cache

Methods with arguments are cached per unique argument combination:

class Matrix(MemoizedClass):
    @memoize
    def power(self, n: int) -> float:
        return self._value ** n

m = Matrix()
m.power(2)  # Cached for n=2
m.power(3)  # Cached separately for n=3

How It Works

Each MemoizedClass instance carries a memoized_results dictionary, initialized in __new__ to support multiple inheritance. The @memoize decorator hashes the function name, positional args, and sorted keyword args into a key. On cache hit, the stored result is returned without calling the function.

Dependencies

None. gri-memoize has no external dependencies.

Other Projects

Current list of other GRI FOSS Projects we are building and maintaining.

License

MIT License. See LICENSE for details.

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

gri_memoize-0.2.3.tar.gz (30.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gri_memoize-0.2.3-py3-none-any.whl (5.6 kB view details)

Uploaded Python 3

File details

Details for the file gri_memoize-0.2.3.tar.gz.

File metadata

  • Download URL: gri_memoize-0.2.3.tar.gz
  • Upload date:
  • Size: 30.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.19 {"installer":{"name":"uv","version":"0.11.19","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for gri_memoize-0.2.3.tar.gz
Algorithm Hash digest
SHA256 bf879c1adf7c4041459a45e2757158828837ee79df99d90205ae71469d7a98bf
MD5 b9a720a861554393977f560453a8690a
BLAKE2b-256 e38da465a87f0eca51d2caa352128001c129c6b63f29b54f788537166cef9fb4

See more details on using hashes here.

File details

Details for the file gri_memoize-0.2.3-py3-none-any.whl.

File metadata

  • Download URL: gri_memoize-0.2.3-py3-none-any.whl
  • Upload date:
  • Size: 5.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.19 {"installer":{"name":"uv","version":"0.11.19","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for gri_memoize-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 50e5bed8640489ba576f7a50f64d93aa249659b75b3978d4befab3f4d73e056d
MD5 e5e1e95df99e17a15726a7117ce606dd
BLAKE2b-256 a5a68c46b8ca2fbe7da505f87295ad6eed967fd8bde879fdd589765eb19c0d0a

See more details on using hashes here.

Supported by

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