Persistent, stale-free, local and cross-machine caching for Python functions.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Cachier provides global configuration functions that allow you to set default parameters for all memoized functions. These settings apply to all cachier decorators unless explicitly overridden by individual decorator parameters.
def set_global_params(**params: Any) -> None:
"""
Configure global parameters applicable to all memoized functions.
This function takes the same keyword parameters as the cachier decorator.
Parameters can be passed all at once or with multiple calls.
Parameters given directly to a decorator take precedence over values
set by this function.
Only 'stale_after', 'next_time', and 'wait_for_calc_timeout' can be changed
after the memoization decorator has been applied. Other parameters will
only have an effect on decorators applied after this function is run.
Parameters:
- **params: Any valid cachier decorator parameter
Valid parameters include:
- caching_enabled: bool - Enable/disable caching globally
- hash_func: HashFunc - Default hash function
- backend: Backend - Default backend type
- mongetter: Optional[Mongetter] - Default MongoDB collection getter
- stale_after: timedelta - Default staleness threshold
- next_time: bool - Default background refresh behavior
- cache_dir: Union[str, os.PathLike] - Default cache directory
- pickle_reload: bool - Default pickle reload behavior
- separate_files: bool - Default separate files behavior
- wait_for_calc_timeout: int - Default calculation timeout
- allow_none: bool - Default None value caching
- cleanup_stale: bool - Default stale cleanup behavior
- cleanup_interval: timedelta - Default cleanup interval
"""def get_global_params() -> Params:
"""
Get current set of global parameters.
Returns:
Params dataclass instance containing all current global settings
"""def enable_caching() -> None:
"""
Enable caching globally.
This affects all cachier-decorated functions. When caching is disabled,
decorated functions execute normally without caching behavior.
"""def disable_caching() -> None:
"""
Disable caching globally.
This affects all cachier-decorated functions. When caching is disabled,
decorated functions execute normally without caching behavior.
"""from cachier import cachier, set_global_params, get_global_params
from datetime import timedelta
import os
# Set global defaults
set_global_params(
backend='pickle',
cache_dir=os.path.expanduser('~/my_app_cache'),
stale_after=timedelta(hours=2),
allow_none=True,
cleanup_stale=True,
cleanup_interval=timedelta(hours=6)
)
# All decorators after this will use these defaults
@cachier() # Uses global settings
def function1(x):
return x * 2
@cachier(stale_after=timedelta(minutes=30)) # Overrides global stale_after
def function2(x):
return x ** 2
# Check current global settings
params = get_global_params()
print(f"Global backend: {params.backend}")
print(f"Global cache_dir: {params.cache_dir}")
print(f"Global stale_after: {params.stale_after}")from cachier import cachier, enable_caching, disable_caching
@cachier()
def cached_operation(data):
return expensive_computation(data)
# Normal cached operation
result1 = cached_operation("test") # Computed and cached
# Temporarily disable caching for all functions
disable_caching()
result2 = cached_operation("test") # Computed again, not cached
# Re-enable caching
enable_caching()
result3 = cached_operation("test") # Uses cache againimport os
from cachier import set_global_params
from datetime import timedelta
# Configure based on environment
if os.getenv('ENVIRONMENT') == 'production':
# Production: Longer cache times, cleanup enabled
set_global_params(
stale_after=timedelta(hours=12),
cleanup_stale=True,
cleanup_interval=timedelta(hours=2),
cache_dir='/var/cache/myapp'
)
elif os.getenv('ENVIRONMENT') == 'development':
# Development: Shorter cache times, no cleanup
set_global_params(
stale_after=timedelta(minutes=5),
cleanup_stale=False,
cache_dir=os.path.expanduser('~/dev_cache')
)
else:
# Testing: Memory backend, no persistence
set_global_params(
backend='memory',
stale_after=timedelta(seconds=30)
)
@cachier() # Will use environment-specific settings
def api_call(endpoint):
return fetch_data(endpoint)from cachier import set_global_params
from datetime import timedelta
# Configure for MongoDB backend
def get_mongo_collection():
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
return client.cache_db.function_cache
set_global_params(
backend='mongo',
mongetter=get_mongo_collection,
wait_for_calc_timeout=30, # 30 seconds max wait
stale_after=timedelta(hours=6)
)
@cachier() # Uses MongoDB backend
def distributed_function(user_id):
return process_user_data(user_id)
# Configure for Redis backend
def get_redis_client():
import redis
return redis.Redis(host='localhost', port=6379, db=0)
set_global_params(
backend='redis',
redis_client=get_redis_client,
stale_after=timedelta(minutes=30)
)
@cachier() # Uses Redis backend
def session_function(session_id):
return get_session_data(session_id)from cachier import set_global_params
from datetime import timedelta
# Set basic defaults
set_global_params(backend='pickle', allow_none=True)
# Later, add cache directory
set_global_params(cache_dir='/opt/cache')
# Later, add staleness configuration
set_global_params(
stale_after=timedelta(hours=1),
cleanup_stale=True
)
# All previous settings are preserved and merged
params = get_global_params()
# params.backend == 'pickle'
# params.allow_none == True
# params.cache_dir == '/opt/cache'
# params.stale_after == timedelta(hours=1)
# params.cleanup_stale == TrueThe Params dataclass contains all configurable global parameters:
@dataclass
class Params:
"""Default definition for cachier parameters."""
caching_enabled: bool = True
hash_func: HashFunc = _default_hash_func
backend: Backend = "pickle"
mongetter: Optional[Mongetter] = None
stale_after: timedelta = timedelta.max
next_time: bool = False
cache_dir: Union[str, os.PathLike] = LazyCacheDir()
pickle_reload: bool = True
separate_files: bool = False
wait_for_calc_timeout: int = 0
allow_none: bool = False
cleanup_stale: bool = False
cleanup_interval: timedelta = timedelta(days=1)For backwards compatibility, cachier maintains deprecated versions of the global configuration functions:
def set_default_params(**params: Any) -> None:
"""
Deprecated: Use set_global_params instead.
Configure default parameters applicable to all memoized functions.
This function emits a DeprecationWarning and calls set_global_params.
"""
def get_default_params() -> Params:
"""
Deprecated: Use get_global_params instead.
Get current set of default parameters.
This function emits a DeprecationWarning and calls get_global_params.
"""Usage of these functions will emit deprecation warnings encouraging migration to the new function names.
Install with Tessl CLI
npx tessl i tessl/pypi-cachier