Skip to main content

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+.

Documentation

The wheel ships its documentation inside the package, in gri_memoize/docs/, so it is available wherever the package is installed:

  • overview.md -- usage, cache invalidation, and gotchas
  • api_summary.md -- every public name and signature (generated)

Print the directory with python -c "import gri_memoize, pathlib; print(pathlib.Path(gri_memoize.__file__).parent / 'docs')". Every example in those files is run by the test suite.

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 per-method 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 builds a key from the function's qualified name, positional args, and sorted keyword args; the args must be hashable. 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.

Release files for gri-memoize 0.2.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gri-memoize 0.2.4
File Size Uploaded
gri_memoize-0.2.4.tar.gz 17.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for gri-memoize 0.2.4
File Interpreter ABI Platform
gri_memoize-0.2.4-py3-none-any.whl Python 3 none any Details

Total release size: 26.1 kB

Release files / gri_memoize-0.2.4.tar.gz

Download URL gri_memoize-0.2.4.tar.gz
Size 17.5 kB
Tags Source
SHA-256 checksum
How to use checksums
ea8303055b6ace4a91cd8bb804407651c8d5d4ce549a22089ead9ada77158839
BLAKE2b-256 checksum
How to use checksums
cac86cba7cca4de596ceff37a6a66042c2089ebf03871b33b8d92b0beec351d3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / gri_memoize-0.2.4-py3-none-any.whl

Download URL gri_memoize-0.2.4-py3-none-any.whl
Size 8.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
332b5307fb0c92e3aac1347e9d0a9e8e337cbe20e889006060d1a21695761bcb
BLAKE2b-256 checksum
How to use checksums
f7ad0b6dfa4e9a7c8194b33dcd1aa53a2ee239b4424408372665e2ff8e3047f3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release history Release notifications | RSS feed

This release

0.2.4 This release

2 release files

0.2.3

2 release files

0.2.2

2 release files

0.2.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page