Reputation: 2694
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?
Upvotes: 2
Views: 1790
Reputation: 1242
Here is a custom class for a variable with a timeout, without the need to install a third-party package:
import time
class TimeoutVar:
"""Variable whose values time out."""
def __init__(self, value, timeout):
"""Store the timeout and value."""
self._value = value
self._last_set = time.time()
self.timeout = timeout
@property
def value(self):
"""Get the value if the value hasn't timed out."""
if time.time() - self._last_set < self.timeout:
return self._value
@value.setter
def value(self, value, timeout=None):
"""Set the value while resetting the timer."""
self._value = value
self._last_set = time.time()
if timeout is not None:
self.timeout = timeout
You can save this in a file, say timeout_var.py
, then import the class in your code. This can be used as follows:
import time
from timeout_var import TimeoutVar
var = TimeoutVar(value=3, timeout=5)
print(var.value)
time.sleep(5)
print(var.value)
var.value = 7
print(var.value)
time.sleep(5)
print(var.value)
The output is:
3
None
7
None
When you assign the value
attribute a new value, the internal timer is also reset.
Upvotes: 3
Reputation: 9504
Try ExpiringDict
. It allows you to define a dictionary with key's expiration.
First, install the package:
pip install expiringdict
Here is an example for basic usage:
import time
from expiringdict import ExpiringDict
vars_with_expiry = ExpiringDict(max_age_seconds=1, max_len=100)
vars_with_expiry["my_var"] = "hello"
print(vars_with_expiry.get("my_var")) # hello
time.sleep(2)
print(vars_with_expiry.get("my_var")) # None
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 the sleep
.
Upvotes: 2