Skip to content
Python TTL Dictionary - dictionary with key expiry time
Python Makefile
Branch: master
Clone or download
Pull request Compare This branch is 39 commits ahead of jvtm:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.


Python dictionary with key expiry time

OrderedTTLDict - behaves like an ordered dict you know. The methods items and values return a list of objects after purging expired objects. The method keys returns odict_keys as the parent class, but it does so after purging expired keys. Python's own OrderedDict and other dictionaries return a dictionary views whereas the methods here do not.

Expired keys are not removed, instead they are expired. You can remove expired keys by calling keys() or any other method that iterates over the dictionary instance. Expired keys will be removed when you try to access them.


In [1]: from ttldict import  TTLOrderedDict

In [2]: mydict = TTLOrderedDict(default_ttl=3)  # expire keys after 3 second

In [3]: mydict['foo'] = 'bar'

In [4]: mydict.is_expired('foo')  # not yet expired

In [5]: mydict.is_expired('foo')  # not yet expired

In [6]: mydict.is_expired('foo')  # expired !!!
Out[6]: 'foo'

In [7]: mydict['foo']
KeyError                                  Traceback (most recent call last)
<ipython-input-55-ed0618fdfbab> in <module>()
----> 1 mydict['foo']

/..../ttldict/ in __getitem__(self, key)
     95             if self.is_expired(key):
     96                 self.__delitem__(key)
---> 97                 raise KeyError
     98             item = super().__getitem__(key)[1]
     99             return item


In [8]: mydict.is_expired('foo')  # not available anymore
KeyError                                  Traceback (most recent call last)
<ipython-input-56-351121feac66> in <module>()
----> 1 mydict.is_expired('foo')  # not available anymore

.../ttldict/ in is_expired(self, key, now)
     59                 now = time.time()
---> 61             expire, _value = super().__getitem__(key)
     63             if expire:

KeyError: 'foo'


Use pytest to run the tests:

make test

Credits and Thanks:

and for Jyrki Muukkonen for ttldict published in

This library contains fixes for his TTLDict class and my own OrderedTTLDict.

Without all those this work would not have been possible.

You can’t perform that action at this time.