Expiring dict

Posted by Afsal on 10-Mar-2023

Hi Pythonistas!

Today we will learn about a simple but interesting package that is expiring-dict. This can be used as a caching mechanism. We can add expiry to any key in this dict. Once the expiry time is reached that key will be removed. Expiry can be set at dictionary level or key level. Let us learn with an example

Installation

pip install expiring-dict

Expiry set all dict level

from time import sleep
from expiring_dict import ExpiringDict

cache = ExpiringDict(1)  # Keys will exist for 1-second
cache["key"] = "value"
print(cache.get("key"))
sleep(2)
print(cache.get("key"))

Output

value
None

Here we are creating an expiring dict with one-second expiry. Every key in this dict exists here only for 1 second. When we get the key the first time we get value as the output but after 2 seconds the same returns None.

Expiry set all key levels

In some cases we do not want to set expiry for entire dict, but for certain keys, this package has these features also

Code

from time import sleep
from expiring_dict import ExpiringDict

cache = ExpiringDict() 
cache["permanent_key"] = "persistent value"
cache.ttl("expiring_key", "expiring value", 1)  # This will expire after 1-second
print(cache.get("permanent_key"))
print(cache.get("expiring_key"))
sleep(2)
print(cache.get("permanent_key"))
print(cache.get("expiring_key"))

Output

persistent value
expiring value
persistent value
None

Here in this example permanent_key acts like a normal key for the dict. But expring_key has expiry for 1 second. After 2 seconds if we check the dict expiring_key returns None but the permanent key remains the same

This can be used as a cache. Hope you have learned something from this post. Please share your valuable suggestions and topic to learn with afsal@pareseltongue.co.in