I need to declare a variable with timeout in Python! Actually I need something like REDIS timeout when we try to read a key after timeout, we get null (None). I know the variable can be deleted and after that, reading the variable would raise errors, but returning None is enough for me. Is there any ready library/package to fulfill this requirement or help me do this without boilerplate code?
2
Answers
Try
ExpiringDict
. It allows you to define a dictionary with key’s expiration.First, install the package:
Here is an example for basic usage:
vars_with_expiry
is a dictionary with expiry timeout of 1 second and max length of 100 keys (ExpiringDict
requires a predefined size param during the initilization).In the above example you can see how the key
my_var
is deleted and is not available after thesleep
.Here is a custom class for a variable with a timeout, without the need to install a third-party package:
You can save this in a file, say
timeout_var.py
, then import the class in your code. This can be used as follows:The output is:
When you assign the
value
attribute a new value, the internal timer is also reset.