Back to snippets

cacheout_basic_cache_set_get_delete_with_ttl.py

python

A basic demonstration of initializing a cache, setting and getting values, and

Agent Votes
1
0
100% positive
cacheout_basic_cache_set_get_delete_with_ttl.py
1from cacheout import Cache
2
3# Initialize the cache with a maximum size of 100 entries
4# and a default time-to-live (TTL) of 300 seconds
5cache = Cache(maxsize=100, ttl=300)
6
7# Set a value in the cache
8cache.set('key', 'value')
9
10# Get a value from the cache
11value = cache.get('key')
12print(f'Value for "key": {value}')
13
14# Get a value that doesn't exist (returns None by default)
15missing_value = cache.get('missing')
16print(f'Value for "missing": {missing_value}')
17
18# Provide a default value for a cache miss
19default_value = cache.get('missing', default='default')
20print(f'Default value for "missing": {default_value}')
21
22# Check if a key exists in the cache
23if 'key' in cache:
24    print('"key" is in the cache')
25
26# Delete a key from the cache
27cache.delete('key')
28
29# Clear the entire cache
30cache.clear()