2

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 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

@timgeb the OP didn't mention that it should be part of the standard library.
@timgeb I've updated my solution with info regarding the installation of the package. Thanks for your feedback!
Your solution is ok for me. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.