Methodtools

0.4.7 · active · verified Thu Apr 09

Methodtools extends standard `functools` functionality to class methods, providing decorators like `cached_method`, `lru_method`, `weak_method`, and `locked_method`. It simplifies applying common patterns (caching, locking) directly to instance methods. It is currently at version 0.4.7 and has an active, consistent release cadence.

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `cached_method` to memoize the result of an instance method. Subsequent calls with the same arguments will return the cached result without re-executing the method logic. The cache is managed per instance.

from methodtools import cached_method

class MyClass:
    def __init__(self, value):
        self._value = value
        self._compute_count = 0

    @cached_method
    def compute_something(self):
        """A method that computes something expensive."""
        self._compute_count += 1
        return self._value * 2

obj = MyClass(10)
print(f"First call: {obj.compute_something()}")
print(f"Second call (cached): {obj.compute_something()}")
print(f"Compute count (should be 1): {obj._compute_count}")

obj2 = MyClass(20)
print(f"First call for obj2: {obj2.compute_something()}")
print(f"Compute count for obj2 (should be 1): {obj2._compute_count}")

view raw JSON →