imgutils.utils.cache

This module provides a thread-safe version of Python’s built-in lru_cache decorator.

The main component of this module is the ts_lru_cache decorator, which wraps the standard lru_cache with thread-safe functionality. This is particularly useful in multi-threaded environments where cache access needs to be synchronized to prevent race conditions.

Usage:
>>> from imgutils.utils import ts_lru_cache
...
>>> @ts_lru_cache(maxsize=100)
>>> def expensive_function(x, y):
...     # Some expensive computation
...     return x + y

ts_lru_cache

imgutils.utils.cache.ts_lru_cache(level: Literal['global', 'process', 'thread'] = 'global', **options)[source]

A thread-safe version of the lru_cache decorator.

This decorator wraps the standard lru_cache with a threading lock to ensure thread-safety in multithreaded environments. It maintains the same interface as the built-in lru_cache, allowing you to specify options like maxsize.

Parameters:
  • level (LevelTyping) – The caching level (‘global’, ‘process’, or ‘thread’).

  • options (dict) – Keyword arguments to be passed to the underlying lru_cache.

Returns:

A thread-safe cached version of the decorated function.

Return type:

function

Example:
>>> @ts_lru_cache(level='thread', maxsize=100)
>>> def my_function(x, y):
...     # Function implementation
...     return x + y

Note

The decorator provides three levels of caching:

  • global: Single cache shared across all processes and threads

  • process: Separate cache for each process

  • thread: Separate cache for each thread

Note

While this decorator ensures thread-safety, it may introduce some overhead due to lock acquisition. Use it when thread-safety is more critical than maximum performance in multithreaded scenarios.

Note

The decorator preserves the cache_info() and cache_clear() methods from the original lru_cache implementation.