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
. .init_venv.sh

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.2.tar.gz (27.7 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.2-py3-none-any.whl (5.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: gri_memoize-0.2.2.tar.gz
  • Upload date:
  • Size: 27.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.6 {"installer":{"name":"uv","version":"0.11.6","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.2.tar.gz
Algorithm Hash digest
SHA256 ef182d4b6cfaff1baa813a1f32226432f004ee30274cc2d262be74d5105da857
MD5 fe35ef6493d31422f7be27b2f6469467
BLAKE2b-256 d02995d7a59470a4e98a291a5563e507e98fe651c35019a9aea0461c0d1d1132

See more details on using hashes here.

File details

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

File metadata

  • Download URL: gri_memoize-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 5.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.6 {"installer":{"name":"uv","version":"0.11.6","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.2-py3-none-any.whl
Algorithm Hash digest
SHA256 be1e6103195ed6fa0ee4dfa1f005987e0b57f2213903ada10a1238e82195bc9f
MD5 022b80179900a13a167877f690db4719
BLAKE2b-256 2b2673eb3b8880b8f78d80693a4d9590ec77db7ef85ccf9834605f30ea3362fe

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