### Initialize and Use LRUCache Source: https://github.com/dgilland/cacheout/blob/master/docs/lru.md Demonstrates how to instantiate an LRUCache and perform basic operations like setting and getting values. ```python from cacheout import LRUCache # Initialize cache with max size of 100 cache = LRUCache(maxsize=100) # Set a value cache.set('key', 'value') # Get a value val = cache.get('key') # Add if not exists cache.add('new_key', 'new_value') ``` -------------------------------- ### Set and Get Cache Entries with TTL - Python Source: https://context7.com/dgilland/cacheout/llms.txt Explains how to use the set() and get() methods for storing and retrieving cache entries. It covers setting entries with optional per-entry TTL, retrieving values with default fallbacks (including callable defaults), and checking the remaining TTL of an entry. ```python from cacheout import Cache import time cache = Cache() # Set a cache entry cache.set("user:123", {"name": "John", "email": "john@example.com"}) # Set with custom TTL (expires in 60 seconds) cache.set("session:abc", {"token": "xyz"}, ttl=60) # Get a cache entry user = cache.get("user:123") print(user) # Output: {'name': 'John', 'email': 'john@example.com'} # Get with default value for missing keys value = cache.get("missing_key", default="not found") print(value) # Output: not found # Get with callable default (value is stored in cache) def compute_value(key): return f"computed_{key}" result = cache.get("computed_key", default=compute_value) print(result) # Output: computed_computed_key print("computed_key" in cache) # Output: True # Check remaining TTL cache.set("temp", "data", ttl=10) remaining = cache.get_ttl("temp") print(f"TTL remaining: {remaining:.2f} seconds") # Output: TTL remaining: ~10.00 seconds ``` -------------------------------- ### Iterate Over Cache Keys and Get Values Source: https://github.com/dgilland/cacheout/blob/master/README.rst Shows how to iterate through all keys in the cache and retrieve their corresponding values using a for loop and the `get` method. ```python for key in cache: print(key, cache.get(key)) ``` -------------------------------- ### Perform Basic Cache Operations Source: https://github.com/dgilland/cacheout/blob/master/docs/index.md Shows how to set, retrieve, and handle missing keys using the set and get methods. ```python cache.set(1, 'foobar') assert cache.get(1) == 'foobar' # Handling missing keys assert cache.get(2) is None assert cache.get(2, default=False) is False # Using a callable for default values assert cache.get(2, default=lambda key: key) == 2 ``` -------------------------------- ### Perform Basic Cache Operations Source: https://context7.com/dgilland/cacheout/llms.txt Demonstrates setting and getting key-value pairs from the cache. It shows how cache hits and misses are registered. ```python cache.set("key1", "value1") cache.set("key2", "value2") cache.get("key1") # Hit cache.get("key1") # Hit cache.get("key2") # Hit cache.get("key3") # Miss cache.get("key4") # Miss ``` -------------------------------- ### Define Cache Event Callbacks Source: https://github.com/dgilland/cacheout/blob/master/README.rst Provides example function signatures for defining callbacks that are triggered on cache events such as getting, setting, or deleting an item. ```python def on_get(key, value, exists): pass def on_set(key, new_value, old_value): pass def on_delete(key, value, cause): pass ``` -------------------------------- ### LFUCache Initialization and Basic Usage (Python) Source: https://github.com/dgilland/cacheout/blob/master/docs/lfu.md Demonstrates how to initialize an LFUCache with various options and perform basic operations like setting and getting cache entries. The LFUCache evicts entries based on the least frequently used policy. ```python from cacheout import LFUCache # Initialize LFU Cache with a maximum size of 100 and a default TTL of 60 seconds lfu_cache = LFUCache(maxsize=100, ttl=60) # Set a key-value pair lfu_cache.set('my_key', 'my_value') # Get a value by key value = lfu_cache.get('my_key') print(f'Value for my_key: {value}') # Add a key only if it doesn't exist lfu_cache.add('new_key', 'new_value') # Delete a key lfu_cache.delete('my_key') # Clear the cache lfu_cache.clear() ``` -------------------------------- ### Add and Get Cache Entries - Python Source: https://github.com/dgilland/cacheout/blob/master/docs/lifo.md Demonstrates adding single or multiple key-value pairs to the LIFOCache. The `add` method only adds if the key does not exist, preserving its TTL. `add_many` allows bulk insertion. The `get` method retrieves a value by key, returning a default if the key is not found or has expired. ```python cache.add('my_key', 'my_value') cache.add_many({'key1': 'value1', 'key2': 'value2'}) value = cache.get('my_key') print(value) ``` -------------------------------- ### Bulk Operations and Filtering Source: https://github.com/dgilland/cacheout/blob/master/README.rst Demonstrates performing bulk set, get, and delete operations, including filtering keys using strings, regex, or lambda functions. ```python import re cache.set_many({'a_1': 1, 'a_2': 2, '123': 3}) # Bulk get with filtering results = cache.get_many(re.compile(r'\d')) # Bulk delete cache.delete_many('a_*') ``` -------------------------------- ### Register Cache Event Callbacks Source: https://context7.com/dgilland/cacheout/llms.txt Demonstrates how to hook into cache operations (get, set, delete) using callback functions to monitor cache activity and eviction reasons. ```python from cacheout import Cache, RemovalCause # Define callback functions def on_get(key, value, exists): status = "HIT" if exists else "MISS" print(f"GET [{status}] {key} = {value}") def on_set(key, new_value, old_value): if old_value is not None: print(f"SET {key}: {old_value} -> {new_value}") else: print(f"SET {key} = {new_value}") def on_delete(key, value, cause): cause_str = { RemovalCause.DELETE: "explicit delete", RemovalCause.EXPIRED: "TTL expired", RemovalCause.FULL: "cache full", RemovalCause.POPITEM: "popitem called" } print(f"DELETE {key} = {value} (reason: {cause_str[cause]})") # Create cache with callbacks cache = Cache( maxsize=3, on_get=on_get, on_set=on_set, on_delete=on_delete ) # Operations trigger callbacks cache.set("a", 1) # Output: SET a = 1 cache.set("b", 2) # Output: SET b = 2 cache.set("a", 10) # Output: SET a: 1 -> 10 cache.get("a") # Output: GET [HIT] a = 10 cache.get("missing") # Output: GET [MISS] missing = None cache.delete("a") # Output: DELETE a = 10 (reason: explicit delete) # Eviction triggers callback cache.set("c", 3) cache.set("d", 4) cache.set("e", 5) # 'b' evicted - Output: DELETE b = 2 (reason: cache full) ``` -------------------------------- ### get Source: https://github.com/dgilland/cacheout/blob/master/docs/lifo.md Retrieves the value associated with a key. Returns a default value if the key is not found or has expired. ```APIDOC ## GET /cacheout/lifo/get ### Description Return the cache value for a key or a default value if the key doesn’t exist or has expired. ### Method GET ### Endpoint `/cacheout/lifo/get` ### Parameters #### Query Parameters - **key** (Hashable) - Required - The cache key to retrieve. - **default** (Any) - Optional - The value to return if the key is not found or expired. If this value is callable, its return value will be used and set for the key. Defaults to None. ### Response #### Success Response (200) - **value** (Any) - The cached value associated with the key, or the default value if not found or expired. ``` -------------------------------- ### Performing Bulk Cache Operations Source: https://github.com/dgilland/cacheout/blob/master/docs/index.md Shows how to efficiently set, get, and delete multiple key-value pairs at once using `cache.set_many()`, `cache.get_many()`, and `cache.delete_many()`. This is more performant than individual operations for large sets of data. ```python cache.set_many({'a': 1, 'b': 2, 'c': 3}) assert cache.get_many(['a', 'b', 'c']) == {'a': 1, 'b': 2, 'c': 3} cache.delete_many(['a', 'b', 'c']) assert cache.count() == 0 ``` -------------------------------- ### Initialize LIFOCache - Python Source: https://github.com/dgilland/cacheout/blob/master/docs/lifo.md Initializes a LIFOCache instance with specified parameters such as max size, time-to-live (TTL), and custom timer functions. It supports optional callbacks for get, set, and delete operations, and can track cache statistics. ```python from cacheout.lifo import LIFOCache # Example initialization cache = LIFOCache(maxsize=1000, ttl=60, enable_stats=True) ``` -------------------------------- ### Get All Cache Keys Source: https://github.com/dgilland/cacheout/blob/master/docs/lfu.md Returns a dictionary keys view of all keys present in the cache. The cache is copied from the underlying storage before returning the keys. ```python def keys() -> KeysView: """Return `dict_keys` view of all cache keys.""" ``` -------------------------------- ### Bulk Operations (Set, Get, Delete) - Python Source: https://context7.com/dgilland/cacheout/llms.txt Demonstrates efficient bulk operations using set_many(), get_many(), and delete_many(). These methods support various filtering mechanisms including lists of keys, wildcard patterns, regular expressions, and custom filter functions for targeted operations. ```python import re from cacheout import Cache cache = Cache() # Set multiple entries at once cache.set_many({ "api:user:1": {"id": 1, "name": "Alice"}, "api:user:2": {"id": 2, "name": "Bob"}, "api:post:1": {"id": 1, "title": "Hello"}, "api:post:2": {"id": 2, "title": "World"}, "config:timeout": 30 }) # Get multiple by list of keys users = cache.get_many(["api:user:1", "api:user:2"]) print(users) # Output: {'api:user:1': {...}, 'api:user:2': {...}} # Get using wildcard pattern all_posts = cache.get_many("api:post:*") print(all_posts) # Output: {'api:post:1': {...}, 'api:post:2': {...}} # Get using regex pattern pattern = re.compile(r"api:user:\d+") users_regex = cache.get_many(pattern) print(users_regex) # Output: {'api:user:1': {...}, 'api:user:2': {...}} # Get using filter function def is_api_key(key): return key.startswith("api:") api_entries = cache.get_many(is_api_key) print(len(api_entries)) # Output: 4 # Delete multiple entries by pattern deleted_count = cache.delete_many("api:user:*") print(f"Deleted {deleted_count} entries") # Output: Deleted 2 entries ``` -------------------------------- ### Get Cache Keys View - cacheout Source: https://github.com/dgilland/cacheout/blob/master/docs/cache.md Returns a view object of all keys present in the cache. The cache keys are copied from the underlying storage before returning. ```python cache.keys() ``` -------------------------------- ### Retrieve and Interpret Cache Statistics Source: https://context7.com/dgilland/cacheout/llms.txt Shows how to get a snapshot of cache statistics, including hit count, miss count, hit rate, miss rate, entry count, and total access count. The statistics can also be converted to a dictionary. ```python # Get statistics snapshot stats = cache.stats.info() print(f"Hit count: {stats.hit_count}") print(f"Miss count: {stats.miss_count}") print(f"Hit rate: {stats.hit_rate:.2%}") print(f"Miss rate: {stats.miss_rate:.2%}") print(f"Entry count: {stats.entry_count}") print(f"Access count: {stats.access_count}") # Convert stats to dictionary stats_dict = stats.to_dict() print(stats_dict) ``` -------------------------------- ### Initialize and Configure Cache Source: https://github.com/dgilland/cacheout/blob/master/README.rst Demonstrates how to instantiate a Cache object with custom settings like maxsize and TTL, and how to reconfigure it at runtime. ```python from cacheout import Cache import time # Initialize with defaults cache = Cache() # Initialize with custom settings cache = Cache(maxsize=256, ttl=0, timer=time.time, default=None) # Reconfigure at runtime cache.configure(maxsize=1000, ttl=300) ``` -------------------------------- ### Serve Documentation Locally (Python) Source: https://github.com/dgilland/cacheout/blob/master/DEVGUIDE.rst Builds and serves the project's documentation over HTTP for local preview. Allows specifying bind address and port. ```shell inv docs -s|--server [-b|--bind 127.0.0.1] [-p|--port 8000] ``` ```shell inv docs -s ``` ```shell inv docs -s -p 8080 ``` ```shell inv docs -s -b 0.0.0.0 -p 8080 ``` -------------------------------- ### Enable Cache Statistics Source: https://context7.com/dgilland/cacheout/llms.txt Shows how to initialize a cache with statistics tracking enabled to monitor hit/miss rates and other performance metrics. ```python from cacheout import Cache # Create cache with statistics enabled cache = Cache(maxsize=100, enable_stats=True) ``` -------------------------------- ### Create and Configure Cache - Python Source: https://context7.com/dgilland/cacheout/llms.txt Demonstrates how to create a Cache object with default or custom settings for max size, TTL, timer function, default values, and statistics. It also shows how to reconfigure the cache at runtime and check its state. ```python import time from cacheout import Cache # Create a cache with default settings (maxsize=256, no TTL expiration) cache = Cache() # Create a cache with custom settings cache = Cache( maxsize=1000, # Maximum number of entries ttl=300, # Default TTL in seconds (5 minutes) timer=time.time, # Timer function for TTL calculations default=None, # Default value for missing keys enable_stats=True # Enable statistics tracking ) # Reconfigure cache at runtime cache.configure(maxsize=2000, ttl=600) # Check cache state print(f"Cache size: {cache.size()}") # Output: Cache size: 0 print(f"Cache is full: {cache.full()}") # Output: Cache is full: False ``` -------------------------------- ### GET /cache/ttl Source: https://github.com/dgilland/cacheout/blob/master/docs/fifo.md Retrieve the remaining time to live for a specific cache key. ```APIDOC ## GET /cache/ttl ### Description Return the remaining time to live of a key that has a TTL. ### Method GET ### Parameters #### Query Parameters - **key** (Hashable) - Required - The cache key to query. ### Response #### Success Response (200) - **ttl** (int|float|null) - The remaining time to live or null if not found. ``` -------------------------------- ### GET /cache/many Source: https://github.com/dgilland/cacheout/blob/master/docs/fifo.md Retrieve multiple cache values based on an iteratee filter. ```APIDOC ## GET /cache/many ### Description Return many cache values as a dict of key/value pairs filtered by an iteratee. ### Method GET ### Parameters #### Query Parameters - **iteratee** (str|List|Pattern|Callable) - Required - The filter criteria (list of keys, search string, regex, or callable). ### Response #### Success Response (200) - **data** (dict) - A dictionary of key/value pairs matching the filter. ``` -------------------------------- ### Initialize and Configure Cacheout Cache Source: https://github.com/dgilland/cacheout/blob/master/docs/cache.md Demonstrates how to instantiate the Cache class with custom settings such as maxsize and default TTL, and how to update configuration at runtime. ```python from cacheout import Cache # Initialize with custom settings cache = Cache(maxsize=512, ttl=60) # Update configuration at runtime cache.configure(maxsize=1024, ttl=300) ``` -------------------------------- ### Implement FIFO, LIFO, MRU, and RR Cache Strategies Source: https://context7.com/dgilland/cacheout/llms.txt Shows how to initialize and use various cache eviction policies including First-In-First-Out, Last-In-First-Out, Most-Recently-Used, and Random Replacement. ```python from cacheout import FIFOCache, LIFOCache, MRUCache, RRCache # FIFO Cache - First In, First Out (same as base Cache) fifo = FIFOCache(maxsize=3) fifo.set_many({"a": 1, "b": 2, "c": 3}) fifo.set("d", 4) # 'a' is evicted (first in) print(list(fifo.keys())) # Output: ['b', 'c', 'd'] # LIFO Cache - Last In, First Out lifo = LIFOCache(maxsize=3) lifo.set_many({"a": 1, "b": 2, "c": 3}) lifo.set("d", 4) # 'c' is evicted (last in) print(list(lifo.keys())) # Output: ['a', 'b', 'd'] # MRU Cache - Most Recently Used evicted first mru = MRUCache(maxsize=3) mru.set_many({"a": 1, "b": 2, "c": 3}) mru.get("a") # 'a' becomes most recently used mru.set("d", 4) # 'a' is evicted (most recently used) print(list(mru.keys())) # Output: ['b', 'c', 'd'] # RR Cache - Random Replacement rr = RRCache(maxsize=3) rr.set_many({"a": 1, "b": 2, "c": 3}) rr.set("d", 4) # Random entry is evicted print(f"RR cache size: {rr.size()}") # Output: RR cache size: 3 ``` -------------------------------- ### Get Cache Size Source: https://github.com/dgilland/cacheout/blob/master/docs/lfu.md Returns the total number of entries currently stored in the cache. ```python def size() -> int: """Return number of cache entries.""" ``` -------------------------------- ### Initialize and Use CacheManager Source: https://github.com/dgilland/cacheout/blob/master/README.rst Demonstrates how to initialize and use `CacheManager` to manage multiple distinct cache instances with different configurations. ```python from cacheout import CacheManager cacheman = CacheManager({ 'a': {'maxsize': 100}, 'b': {'maxsize': 200, 'ttl': 900}, 'c': {} }) cacheman['a'].set('key1', 'value1') value = cacheman['a'].get('key') cacheman['b'].set('key2', 'value2') assert cacheman['b'].maxsize == 200 assert cacheman['b'].ttl == 900 cacheman['c'].set('key3', 'value3') cacheman.clear_all() for name, cache in cacheman: assert name in cacheman assert len(cache) == 0 ``` -------------------------------- ### Initialize and Configure FIFOCache Source: https://github.com/dgilland/cacheout/blob/master/docs/fifo.md Demonstrates how to instantiate a new FIFOCache object and configure its runtime settings such as maxsize and TTL. ```python from cacheout import FIFOCache # Initialize cache cache = FIFOCache(maxsize=256, ttl=60) # Configure settings at runtime cache.configure(maxsize=500, ttl=300) ``` -------------------------------- ### Configure and Manage Caches with CacheManager Source: https://github.com/dgilland/cacheout/blob/master/docs/manager.md Demonstrates how to initialize CacheManager with bulk settings, update configurations dynamically, register custom cache instances, and perform basic CRUD operations on named caches. ```python from cacheout import CacheManager, Cache # Configure bulk caches during initialization cacheset = CacheManager({"A": {"maxsize": 100}, "B": {"ttl": 90}}) # Replace bulk caches after initialization class MyCache(Cache): pass cacheset.setup({"C": {"cache_class": MyCache}, "D": {}}) # Configure individual cache after initialization cacheset.configure("E", **{"cache_class": MyCache}) # Replace a cache entity cacheset.register("E", Cache()) # Access caches cacheset["C"].set("key1", "value1") cacheset["D"].set("key2", "value2") ``` -------------------------------- ### Build Documentation (Python) Source: https://github.com/dgilland/cacheout/blob/master/DEVGUIDE.rst Generates the project's documentation using the configured tools. The output is placed in the 'docs/_build/' directory. ```shell inv docs ``` -------------------------------- ### Get Remaining TTL for a Key - cacheout Source: https://github.com/dgilland/cacheout/blob/master/docs/cache.md Returns the remaining Time-To-Live (TTL) for a cache key. Returns None if the key does not exist or has expired. ```python cache.get_ttl(key) ``` -------------------------------- ### Get Cache Expirations - cacheout Source: https://github.com/dgilland/cacheout/blob/master/docs/cache.md Retrieves the expiration times for all Time-To-Live (TTL) keys in the cache. Returns a dictionary mapping keys to their expiration timestamps. ```python cache.expire_times() ``` -------------------------------- ### Initialize Cacheout Cache Object Source: https://github.com/dgilland/cacheout/blob/master/docs/index.md Demonstrates how to import and instantiate a Cache object with default or custom configurations such as maxsize and TTL. ```python from cacheout import Cache import time # Basic initialization cache = Cache() # Initialization with custom settings cache = Cache(maxsize=256, ttl=0, timer=time.time, default=None) ``` -------------------------------- ### Set and Verify Multiple Items in Cache Source: https://github.com/dgilland/cacheout/blob/master/README.rst Demonstrates how to efficiently set multiple key-value pairs in the cache using `set_many` and then verifies the contents using `keys`, `values`, and `items`. ```python cache.set_many({'a': 1, 'b': 2, 'c': 3}) assert list(cache.keys()) == ['a', 'b', 'c'] assert list(cache.values()) == [1, 2, 3] assert list(cache.items()) == [('a', 1), ('b', 2), ('c', 3)] ``` -------------------------------- ### Deleting a Cache Key Source: https://github.com/dgilland/cacheout/blob/master/docs/index.md Illustrates how to remove a specific key-value pair from the cache using the `cache.delete()` method. After deletion, attempting to `get` the key will return `None`. ```python cache.delete(1) assert cache.get(1) is None ``` -------------------------------- ### Manage Cache Entries in Python Source: https://context7.com/dgilland/cacheout/llms.txt Demonstrates how to add, delete, and clear cache entries. It also shows how to handle expired entries and check for key existence. ```python from cacheout import Cache import time cache = Cache(ttl=1) cache.set("key1", "value1", ttl=0) cache.set("key2", "value2") cache.set("key3", "value3") deleted = cache.delete("key1") print(f"Deleted: {deleted}") print(cache.has("key1")) print("key2" in cache) time.sleep(1.5) expired_count = cache.delete_expired() print(f"Expired entries removed: {expired_count}") cache.set_many({"a": 1, "b": 2, "c": 3}) cache.clear() print(f"Cache size after clear: {len(cache)}") ``` -------------------------------- ### Get All Cache Values Source: https://github.com/dgilland/cacheout/blob/master/docs/lfu.md Returns a dictionary values view of all values currently stored in the cache. Similar to `items()`, modifications to mutable values will affect the cache. ```python def values() -> ValuesView: """Return `dict_values` view of all cache values.""" ``` -------------------------------- ### Enable and Configure Cache Statistics Source: https://github.com/dgilland/cacheout/blob/master/README.rst Demonstrates how to enable statistics collection for a cache instance, either during initialization or by reconfiguring an existing cache. ```python cache_with_stats = Cache(enable_stats=True) # Or via configure() cache.configure(enable_stats=True) # Or directly via Cache.stats cache.stats.enable() ``` -------------------------------- ### Manage Cache Expiration and Eviction Source: https://github.com/dgilland/cacheout/blob/master/docs/fifo.md Demonstrates how to manually trigger eviction, delete expired keys, and check the expiration status of specific keys. ```python # Remove expired entries and perform policy-based eviction cache.evict() # Remove only expired entries expired_count = cache.delete_expired() # Check if a key is expired is_expired = cache.expired('key2') ``` -------------------------------- ### Get Cache Items View - cacheout Source: https://github.com/dgilland/cacheout/blob/master/docs/cache.md Returns a view object of the cache's items (key-value pairs). Modifications to mutable values in the view will affect the cache. ```python cache.items() ``` -------------------------------- ### Get Multiple Cache Values - cacheout Source: https://github.com/dgilland/cacheout/blob/master/docs/cache.md Retrieves multiple cache values based on an iteratee, which can be a list of keys, a wildcard string, a compiled regex, or a callable function. ```python cache.get_many(iteratee) ``` -------------------------------- ### LFUCache Eviction and Statistics (Python) Source: https://github.com/dgilland/cacheout/blob/master/docs/lfu.md Shows how to configure LFUCache to enable statistics and demonstrates the eviction process. The evict() method first removes expired entries, then removes non-TTL entries based on the LFU policy. ```python from cacheout import LFUCache # Initialize LFU Cache with statistics enabled lfu_cache = LFUCache(maxsize=2, enable_stats=True) lfu_cache.set('key1', 'value1') lfu_cache.set('key2', 'value2') lfu_cache.set('key3', 'value3') # This will trigger eviction # Access keys to influence frequency lfu_cache.get('key1') lfu_cache.get('key1') lfu_cache.get('key2') # Manually trigger eviction (though it happens automatically on set when full) lfu_cache.evict() # Access statistics stats = lfu_cache.stats() print(f'Cache stats: {stats}') ``` -------------------------------- ### Get All Cache Items Source: https://github.com/dgilland/cacheout/blob/master/docs/lfu.md Returns a dictionary items view of all key-value pairs currently stored in the cache. Note that modifications to mutable values in the returned view will affect the cache directly. ```python def items() -> ItemsView: """Return a `dict_items` view of cache items.""" ``` -------------------------------- ### configure Source: https://github.com/dgilland/cacheout/blob/master/docs/lifo.md Allows runtime configuration of cache settings such as maxsize, ttl, and timer. ```APIDOC ## PUT /cacheout/lifo/configure ### Description Configure cache settings at runtime. This method is intended for modifying global cache objects. ### Method PUT ### Endpoint `/cacheout/lifo/configure` ### Parameters #### Request Body - **maxsize** (int | None) - Optional - The new maximum size for the cache. - **ttl** (int | float | None) - Optional - The new default time-to-live for cache entries. - **timer** (Callable[[], int | float] | None) - Optional - A new function to use for timekeeping. - **default** (Any) - Optional - The new default value to return for missing keys. ``` -------------------------------- ### Get Cache Value by Key - cacheout Source: https://github.com/dgilland/cacheout/blob/master/docs/cache.md Retrieves the value associated with a given key. If the key does not exist, has expired, or a default value is provided, it returns the default value or the result of a callable default. ```python cache.get(key, default=None) ``` -------------------------------- ### Get Time To Live (TTL) for Cache Key Source: https://github.com/dgilland/cacheout/blob/master/docs/lfu.md Returns the remaining time to live for a specified cache key. If the key does not exist or has expired, it returns None. The time unit is determined by the timer configuration. ```python def get_ttl(key: Hashable) -> int | float | None: """Return the remaining time to live of a key that has a TTL.""" ``` -------------------------------- ### Run Tests and Builds (Python) Source: https://github.com/dgilland/cacheout/blob/master/DEVGUIDE.rst Executes unit tests and builds the project. This provides a comprehensive check of the project's state. ```shell inv test ``` -------------------------------- ### Managing Multiple Caches with CacheManager Source: https://github.com/dgilland/cacheout/blob/master/docs/index.md Demonstrates the use of `CacheManager` to create and manage multiple distinct cache instances. It shows how to configure individual caches within the manager, access them by name, and perform operations like clearing all caches. ```python from cacheout import CacheManager cacheman = CacheManager({'a': {'maxsize': 100}, 'b': {'maxsize': 200, 'ttl': 900}, 'c': {}}) cacheman['a'].set('key1', 'value1') value = cacheman['a'].get('key') cacheman['b'].set('key2', 'value2') assert cacheman['b'].maxsize == 200 assert cacheman['b'].ttl == 900 cacheman['c'].set('key3', 'value3') cacheman.clear_all() for name, cache in cacheman: assert name in cacheman assert len(cache) == 0 ``` -------------------------------- ### Run All Autoformatters (Python) Source: https://github.com/dgilland/cacheout/blob/master/DEVGUIDE.rst Executes all configured code autoformatters for the project, including black, isort, and docformatter. This ensures consistent code style across the codebase. ```shell inv fmt ``` -------------------------------- ### Get Many Cache Items Source: https://github.com/dgilland/cacheout/blob/master/docs/lfu.md Retrieves multiple cache values based on a provided iteratee. The iteratee can be a list of keys, a wildcard string, a compiled regular expression, or a callable function for custom key matching. Returns a dictionary of matching key-value pairs. ```python def get_many(iteratee: str | List[Hashable] | Pattern | Callable) -> dict: """Return many cache values as a `dict` of key/value pairs filtered by an iteratee.""" ``` -------------------------------- ### Build Package Distribution (Python) Source: https://github.com/dgilland/cacheout/blob/master/DEVGUIDE.rst Builds the source and binary distributions for the Python package. The output is placed in the 'dist/' directory. ```shell inv build ``` -------------------------------- ### Configure Cache TTL and Memoization Source: https://github.com/dgilland/cacheout/blob/master/docs/index.md Explains how to set time-to-live (TTL) for cache entries and how to use the memoize decorator for function result caching. ```python import time # Set entry with TTL cache.set(3, {'data': {}}, ttl=1) time.sleep(1) assert cache.get(3) is None # Memoize a function @cache.memoize(ttl=5, typed=True) def func(a, b): return a + b ``` -------------------------------- ### Basic Cache Operations Source: https://github.com/dgilland/cacheout/blob/master/README.rst Covers setting, retrieving, and deleting individual cache keys, including handling default values for missing keys. ```python cache.set(1, 'foobar') assert cache.get(1) == 'foobar' # Default value handling assert cache.get(2, default=False) is False # Using a callable for default assert cache.get(2, default=lambda key: key) == 2 # Deletion cache.delete(1) cache.clear() ``` -------------------------------- ### Iterate Over Cache Data in Python Source: https://context7.com/dgilland/cacheout/llms.txt Provides methods to retrieve all keys, values, and items from a cache instance. It also demonstrates iteration and popping items. ```python from cacheout import Cache cache = Cache() cache.set_many({"a": 1, "b": 2, "c": 3}) print(list(cache.keys())) print(list(cache.values())) print(list(cache.items())) for key in cache: print(f"{key}: {cache.get(key)}") cache_copy = cache.copy() print(cache_copy) key, value = cache.popitem() print(f"Popped: {key}={value}") ``` -------------------------------- ### Perform Bulk Cache Operations Source: https://github.com/dgilland/cacheout/blob/master/docs/lru.md Shows how to add multiple items to the cache or delete multiple keys using various filtering methods. ```python cache.add_many({'a': 1, 'b': 2, 'c': 3}) # Delete keys using a list cache.delete_many(['a', 'b']) # Delete keys using a wildcard string cache.delete_many('user_*') ``` -------------------------------- ### CacheManager Configuration and Access Source: https://github.com/dgilland/cacheout/blob/master/docs/manager.md Methods for initializing, configuring, and accessing multiple cache instances within the CacheManager. ```APIDOC ## CacheManager Initialization and Management ### Description The CacheManager provides an interface for accessing multiple caches indexed by name. Each named cache is a separate instance with its own configuration. ### Methods - **setup(settings)**: Bulk configuration of caches. WARNING: Destroys all previously configured caches. - **configure(name, **options)**: Configures or creates an individual cache by name. - **register(name, cache)**: Registers a specific cache instance by name. - **clear_all()**: Clears all managed caches. ### Parameters #### setup(settings) - **settings** (dict) - Optional - A dictionary where keys are cache names and values are configuration options. #### configure(name, **options) - **name** (Hashable) - Required - The identifier for the cache. - **options** (Any) - Optional - Configuration parameters for the cache instance. ### Request Example ```python # Bulk configuration manager = CacheManager({"A": {"maxsize": 100}, "B": {"ttl": 90}}) # Individual configuration manager.configure("E", cache_class=MyCache) ``` ### Response #### Success Response (None) - Returns None for configuration methods. Accessing a cache returns a Cache instance. ``` -------------------------------- ### Copying Cache Contents Source: https://github.com/dgilland/cacheout/blob/master/docs/index.md Shows how to create a shallow copy of the entire cache's contents using the `cache.copy()` method. The returned dictionary contains key-value pairs representing the current state of the cache. ```python assert cache.copy() == {1: 'foobar', 2: ('foo', 'bar', 'baz')} ``` -------------------------------- ### Cache Management and Status - Python Source: https://github.com/dgilland/cacheout/blob/master/docs/lifo.md Includes essential cache management functions such as clearing all entries (`clear`), creating a copy of the cache (`copy`), and checking if the cache is full (`full`). It also provides a way to view remaining expiration times for TTL keys (`expire_times`) and to manually trigger eviction (`evict`). ```python cache.clear() new_cache = cache.copy() is_full = cache.full() expirations = cache.expire_times() cache.evict() ``` -------------------------------- ### Implement LRU Cache Policy Source: https://context7.com/dgilland/cacheout/llms.txt Demonstrates the LRUCache class, which automatically evicts the least recently used entries when the cache reaches its maximum size. ```python from cacheout import LRUCache cache = LRUCache(maxsize=3) cache.set("a", 1) cache.set("b", 2) cache.set("c", 3) cache.get("a") cache.set("d", 4) print(list(cache.keys())) print(cache.get("b")) ``` -------------------------------- ### Reconfiguring Cache Object Source: https://github.com/dgilland/cacheout/blob/master/docs/index.md Demonstrates how to modify the configuration of an existing cache object after its creation using the `cache.configure()` method. This allows dynamic adjustment of parameters like `maxsize` and `ttl`. ```python cache.configure(maxsize=1000, ttl=5 * 60) ``` -------------------------------- ### Implement LFU Cache Strategy Source: https://context7.com/dgilland/cacheout/llms.txt Demonstrates the use of the Least Frequently Used (LFU) cache. It tracks access counts and evicts the least frequently accessed items when the cache reaches its maximum size. ```python from cacheout import LFUCache cache = LFUCache(maxsize=3) # Add entries cache.set("rare", "rarely accessed") cache.set("common", "commonly accessed") cache.set("popular", "very popular") # Access entries different number of times cache.get("popular") # Access count: 2 cache.get("popular") # Access count: 3 cache.get("common") # Access count: 2 # Add new entry - 'rare' is evicted (least frequently used) cache.set("new", "new entry") print(list(cache.keys())) # Output: ['common', 'popular', 'new'] print(cache.get("rare")) # Output: None (evicted) ``` -------------------------------- ### Run Individual Autoformatters (Python) Source: https://github.com/dgilland/cacheout/blob/master/DEVGUIDE.rst Runs specific autoformatting tools individually. Useful for targeted code style adjustments. ```shell inv black ``` ```shell inv isort ``` ```shell inv docformatter ``` -------------------------------- ### Clean Build and Temporary Files (Python) Source: https://github.com/dgilland/cacheout/blob/master/DEVGUIDE.rst Removes all build artifacts, temporary files, and cache directories. This ensures a clean state for subsequent builds or development. ```shell inv clean ``` -------------------------------- ### copy Source: https://github.com/dgilland/cacheout/blob/master/docs/lifo.md Creates and returns a shallow copy of the current cache state. ```APIDOC ## GET /cacheout/lifo/copy ### Description Return a copy of the cache. ### Method GET ### Endpoint `/cacheout/lifo/copy` ### Response #### Success Response (200) - **cache_copy** (OrderedDict) - A shallow copy of the cache. ``` -------------------------------- ### Using Complex Filtering with Bulk Operations Source: https://github.com/dgilland/cacheout/blob/master/docs/index.md Explains how to use regular expressions or lambda functions with `cache.get_many()` and `cache.delete_many()` for advanced filtering of cache entries. This allows for targeted retrieval or deletion based on complex criteria. ```python import re cache.set_many({'a_1': 1, 'a_2': 2, '123': 3, 'b': 4}) cache.get_many('a_*') == {'a_1': 1, 'a_2': 2} cache.get_many(re.compile(r'\d')) == {'123': 3} cache.get_many(lambda key: '2' in key) == {'a_2': 2, '123': 3} cache.delete_many('a_*') assert dict(cache.items()) == {'123': 3, 'b': 4} ``` -------------------------------- ### LFUCache Advanced Operations (Python) Source: https://github.com/dgilland/cacheout/blob/master/docs/lfu.md Illustrates advanced functionalities of the LFUCache, including adding multiple items, deleting items by various criteria, checking cache status, and managing expirations. ```python from cacheout import LFUCache import re lfu_cache = LFUCache(maxsize=5) lfu_cache.set_many({'key1': 'val1', 'key2': 'val2'}) # Delete multiple keys using a list lfu_cache.delete_many(['key1', 'key2']) # Delete keys matching a pattern lfu_cache.set({'key3': 'val3', 'key4': 'val4'}) pattern = re.compile('key.*') lfu_cache.delete_many(pattern) # Check if cache is full is_full = lfu_cache.full() # Check if a key has expired lfu_cache.set('temp_key', 'temp_val', ttl=1) # time.sleep(1.1) # Simulate time passing is_expired = lfu_cache.expired('temp_key') # Get expiration times exp_times = lfu_cache.expire_times() # Delete expired entries lfu_cache.delete_expired() ``` -------------------------------- ### Configure and Check Expiration - Python Source: https://github.com/dgilland/cacheout/blob/master/docs/lifo.md Allows runtime configuration of cache parameters like `maxsize`, `ttl`, and `timer`. The `expired` method checks if a specific key has expired, optionally using a provided timestamp for the expiration check. ```python cache.configure(maxsize=500, ttl=120) is_expired = cache.expired('my_key') ``` -------------------------------- ### Run Individual Linters (Python) Source: https://github.com/dgilland/cacheout/blob/master/DEVGUIDE.rst Runs specific linting tools individually. Useful for diagnosing specific code quality issues. ```shell inv flake8 ``` ```shell inv pylint ``` ```shell inv mypy ``` -------------------------------- ### Release Package to PyPI (Python) Source: https://github.com/dgilland/cacheout/blob/master/DEVGUIDE.rst Automates the process of releasing a new version of the package to the Python Package Index (PyPI). ```shell inv release ``` -------------------------------- ### Clearing the Entire Cache Source: https://github.com/dgilland/cacheout/blob/master/docs/index.md Demonstrates how to empty the cache completely using the `cache.clear()` method. This removes all stored key-value pairs, resulting in an empty cache. ```python cache.clear() assert len(cache) == 0 ``` -------------------------------- ### add Source: https://github.com/dgilland/cacheout/blob/master/docs/lifo.md Adds a key-value pair to the cache if the key does not already exist. If the key exists, the operation is ignored, preserving the original TTL. ```APIDOC ## POST /cacheout/lifo/add ### Description Add cache key/value if it doesn’t already exist. This method ignores keys that exist which leaves the original TTL in tact. ### Method POST ### Endpoint `/cacheout/lifo/add` ### Parameters #### Request Body - **key** (Hashable) - Required - Cache key to add. - **value** (Any) - Required - Cache value. - **ttl** (int | float | None) - Optional - TTL value. Defaults to `None` which uses the cache's default TTL. Time units are determined by `timer`. ``` -------------------------------- ### Run All Linters (Python) Source: https://github.com/dgilland/cacheout/blob/master/DEVGUIDE.rst Executes all configured code linters for the project, including flake8, pylint, and mypy. This helps identify potential errors and enforce code quality standards. ```shell inv lint ```