0
# Global Configuration
1
2
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.
3
4
## Capabilities
5
6
### Set Global Parameters
7
8
```python { .api }
9
def set_global_params(**params: Any) -> None:
10
"""
11
Configure global parameters applicable to all memoized functions.
12
13
This function takes the same keyword parameters as the cachier decorator.
14
Parameters can be passed all at once or with multiple calls.
15
Parameters given directly to a decorator take precedence over values
16
set by this function.
17
18
Only 'stale_after', 'next_time', and 'wait_for_calc_timeout' can be changed
19
after the memoization decorator has been applied. Other parameters will
20
only have an effect on decorators applied after this function is run.
21
22
Parameters:
23
- **params: Any valid cachier decorator parameter
24
25
Valid parameters include:
26
- caching_enabled: bool - Enable/disable caching globally
27
- hash_func: HashFunc - Default hash function
28
- backend: Backend - Default backend type
29
- mongetter: Optional[Mongetter] - Default MongoDB collection getter
30
- stale_after: timedelta - Default staleness threshold
31
- next_time: bool - Default background refresh behavior
32
- cache_dir: Union[str, os.PathLike] - Default cache directory
33
- pickle_reload: bool - Default pickle reload behavior
34
- separate_files: bool - Default separate files behavior
35
- wait_for_calc_timeout: int - Default calculation timeout
36
- allow_none: bool - Default None value caching
37
- cleanup_stale: bool - Default stale cleanup behavior
38
- cleanup_interval: timedelta - Default cleanup interval
39
"""
40
```
41
42
### Get Global Parameters
43
44
```python { .api }
45
def get_global_params() -> Params:
46
"""
47
Get current set of global parameters.
48
49
Returns:
50
Params dataclass instance containing all current global settings
51
"""
52
```
53
54
### Enable Caching
55
56
```python { .api }
57
def enable_caching() -> None:
58
"""
59
Enable caching globally.
60
61
This affects all cachier-decorated functions. When caching is disabled,
62
decorated functions execute normally without caching behavior.
63
"""
64
```
65
66
### Disable Caching
67
68
```python { .api }
69
def disable_caching() -> None:
70
"""
71
Disable caching globally.
72
73
This affects all cachier-decorated functions. When caching is disabled,
74
decorated functions execute normally without caching behavior.
75
"""
76
```
77
78
## Usage Examples
79
80
### Basic Global Configuration
81
82
```python
83
from cachier import cachier, set_global_params, get_global_params
84
from datetime import timedelta
85
import os
86
87
# Set global defaults
88
set_global_params(
89
backend='pickle',
90
cache_dir=os.path.expanduser('~/my_app_cache'),
91
stale_after=timedelta(hours=2),
92
allow_none=True,
93
cleanup_stale=True,
94
cleanup_interval=timedelta(hours=6)
95
)
96
97
# All decorators after this will use these defaults
98
@cachier() # Uses global settings
99
def function1(x):
100
return x * 2
101
102
@cachier(stale_after=timedelta(minutes=30)) # Overrides global stale_after
103
def function2(x):
104
return x ** 2
105
106
# Check current global settings
107
params = get_global_params()
108
print(f"Global backend: {params.backend}")
109
print(f"Global cache_dir: {params.cache_dir}")
110
print(f"Global stale_after: {params.stale_after}")
111
```
112
113
### Dynamic Caching Control
114
115
```python
116
from cachier import cachier, enable_caching, disable_caching
117
118
@cachier()
119
def cached_operation(data):
120
return expensive_computation(data)
121
122
# Normal cached operation
123
result1 = cached_operation("test") # Computed and cached
124
125
# Temporarily disable caching for all functions
126
disable_caching()
127
result2 = cached_operation("test") # Computed again, not cached
128
129
# Re-enable caching
130
enable_caching()
131
result3 = cached_operation("test") # Uses cache again
132
```
133
134
### Environment-Specific Configuration
135
136
```python
137
import os
138
from cachier import set_global_params
139
from datetime import timedelta
140
141
# Configure based on environment
142
if os.getenv('ENVIRONMENT') == 'production':
143
# Production: Longer cache times, cleanup enabled
144
set_global_params(
145
stale_after=timedelta(hours=12),
146
cleanup_stale=True,
147
cleanup_interval=timedelta(hours=2),
148
cache_dir='/var/cache/myapp'
149
)
150
elif os.getenv('ENVIRONMENT') == 'development':
151
# Development: Shorter cache times, no cleanup
152
set_global_params(
153
stale_after=timedelta(minutes=5),
154
cleanup_stale=False,
155
cache_dir=os.path.expanduser('~/dev_cache')
156
)
157
else:
158
# Testing: Memory backend, no persistence
159
set_global_params(
160
backend='memory',
161
stale_after=timedelta(seconds=30)
162
)
163
164
@cachier() # Will use environment-specific settings
165
def api_call(endpoint):
166
return fetch_data(endpoint)
167
```
168
169
### Backend-Specific Global Settings
170
171
```python
172
from cachier import set_global_params
173
from datetime import timedelta
174
175
# Configure for MongoDB backend
176
def get_mongo_collection():
177
import pymongo
178
client = pymongo.MongoClient('mongodb://localhost:27017/')
179
return client.cache_db.function_cache
180
181
set_global_params(
182
backend='mongo',
183
mongetter=get_mongo_collection,
184
wait_for_calc_timeout=30, # 30 seconds max wait
185
stale_after=timedelta(hours=6)
186
)
187
188
@cachier() # Uses MongoDB backend
189
def distributed_function(user_id):
190
return process_user_data(user_id)
191
192
# Configure for Redis backend
193
def get_redis_client():
194
import redis
195
return redis.Redis(host='localhost', port=6379, db=0)
196
197
set_global_params(
198
backend='redis',
199
redis_client=get_redis_client,
200
stale_after=timedelta(minutes=30)
201
)
202
203
@cachier() # Uses Redis backend
204
def session_function(session_id):
205
return get_session_data(session_id)
206
```
207
208
### Incremental Configuration
209
210
```python
211
from cachier import set_global_params
212
from datetime import timedelta
213
214
# Set basic defaults
215
set_global_params(backend='pickle', allow_none=True)
216
217
# Later, add cache directory
218
set_global_params(cache_dir='/opt/cache')
219
220
# Later, add staleness configuration
221
set_global_params(
222
stale_after=timedelta(hours=1),
223
cleanup_stale=True
224
)
225
226
# All previous settings are preserved and merged
227
params = get_global_params()
228
# params.backend == 'pickle'
229
# params.allow_none == True
230
# params.cache_dir == '/opt/cache'
231
# params.stale_after == timedelta(hours=1)
232
# params.cleanup_stale == True
233
```
234
235
## Global Parameters Dataclass
236
237
The `Params` dataclass contains all configurable global parameters:
238
239
```python { .api }
240
@dataclass
241
class Params:
242
"""Default definition for cachier parameters."""
243
244
caching_enabled: bool = True
245
hash_func: HashFunc = _default_hash_func
246
backend: Backend = "pickle"
247
mongetter: Optional[Mongetter] = None
248
stale_after: timedelta = timedelta.max
249
next_time: bool = False
250
cache_dir: Union[str, os.PathLike] = LazyCacheDir()
251
pickle_reload: bool = True
252
separate_files: bool = False
253
wait_for_calc_timeout: int = 0
254
allow_none: bool = False
255
cleanup_stale: bool = False
256
cleanup_interval: timedelta = timedelta(days=1)
257
```
258
259
## Deprecated Functions
260
261
For backwards compatibility, cachier maintains deprecated versions of the global configuration functions:
262
263
```python { .api }
264
def set_default_params(**params: Any) -> None:
265
"""
266
Deprecated: Use set_global_params instead.
267
Configure default parameters applicable to all memoized functions.
268
269
This function emits a DeprecationWarning and calls set_global_params.
270
"""
271
272
def get_default_params() -> Params:
273
"""
274
Deprecated: Use get_global_params instead.
275
Get current set of default parameters.
276
277
This function emits a DeprecationWarning and calls get_global_params.
278
"""
279
```
280
281
Usage of these functions will emit deprecation warnings encouraging migration to the new function names.