PyLRU: Least Recently Used (LRU) Cache

1.3.1 · active · verified Thu Apr 16

Pylru is a pure Python library implementing a Least Recently Used (LRU) cache. It provides a simple dictionary-like interface for `lrucache` and includes classes for wrapping existing dictionary-like objects (`WriteThroughCacheManager`) and functions (`FunctionCacheManager`, `lrudecorator`). The library is efficient, offering constant-time basic operations (lookup, insert, delete). The current version is 1.3.1, with releases happening periodically based on maintenance needs.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates the basic usage of `pylru.lrucache` as a dictionary-like object, showing insertions, lookups, and the LRU eviction policy. It also includes a basic example of the `pylru.lrudecorator` for memoizing function calls.

import pylru

# Create an LRU cache with a maximum size of 3
cache_size = 3
cache = pylru.lrucache(cache_size)

# Insert items into the cache
cache['apple'] = 1
cache['banana'] = 2
cache['cherry'] = 3
print(f"Cache after initial inserts: {list(cache.items())}")

# Access 'apple' - it becomes the most recently used
print(f"Accessed 'apple': {cache['apple']}")
print(f"Cache order after accessing 'apple': {list(cache.keys())}")

# Insert a new item - 'banana' (least recently used) should be evicted
cache['date'] = 4
print(f"Cache after adding 'date': {list(cache.items())}")

# Test for membership
print(f"Is 'cherry' in cache? {'cherry' in cache}")
print(f"Is 'banana' in cache? {'banana' in cache}")

# Using the lrudecorator
@pylru.lrudecorator(max_size=2)
def fibonacci(n):
    print(f"Computing fibonacci({n})...")
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print("\n--- Decorator Example ---")
print(f"Fib(3): {fibonacci(3)}") # Computes
print(f"Fib(2): {fibonacci(2)}") # Computes
print(f"Fib(3): {fibonacci(3)}") # From cache (most recent)
print(f"Fib(4): {fibonacci(4)}") # Computes, fib(2) gets evicted as LRU

view raw JSON →