Mark As Completed Discussion

Having the ability to set expiration times for keys can be especially useful in scenarios where your data's relevance diminishes over time, like in stock market data, weather forecasts, or caching scenarios. This approach is often found in databases like Redis, and we'll be incorporating it into our own store.

Take for example, monitoring the stock price of a company: if you're tracking Apple Inc. (AAPL) and set a 10-second expiration on the data, a subsequent retrieval after this duration would indicate the data has already expired, necessitating a fresh fetch of the current stock price. This ensures that you're working with the most recent and relevant data and not stale information

In Python, we can extend the built-in dict type to develop a dictionary which allows us to set an expiry time for keys. Whenever we attempt to retrieve a key, we check if the current time is later than the expiry time for that key. If it is, we delete the key and raise a KeyError, otherwise we return the key's value. Thus, the basic logic to set the value with an expiration time includes additional steps.

Here's Python logic of how we might implement this expiration feature. The code demonstrates how if we try to access the 'AAPL' key in our ExpiringDict after its expiry time of 10 seconds, we get a 'Key expired' message.

Let's run this code to simulate key expiration in our key-value store.

PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment