Time-to-live is what separates a dict from an actual cache. Add:
put(key, value, ttl_seconds=None) β if ttl_seconds is set, the key expires after that many secondsget(key) β should return None (and delete the key) if it has expiredttl(key) β return remaining seconds, or -1 if no TTL, or -2 if the key is missingThis mirrors how Redis exposes TTL.
import time
class KeyValueStore:
def __init__(self):
self._store = {}
def put(self, key, value, ttl_seconds=None):
"""Store a key-value pair with optional TTL."""
# TODO: Store the value together with an expiry timestamp
# Hint: store a dict like {"value": value, "expiry": expiry_or_None}
pass
def get(self, key):
"""Get value. Return None if missing or expired."""
# TODO: Check if the key exists and has not expired
# If expired, delete it and return None
pass
def delete(self, key):
if key in self._store:
del self._store[key]
return True
return False
def size(self):
return len(self._store)
def ttl(self, key):
"""Return remaining TTL in seconds. -1 if no TTL. -2 if key missing."""
# TODO: Implement this
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Time-to-live is what separates a dict from an actual cache. Add:
put(key, value, ttl_seconds=None) β if ttl_seconds is set, the key expires after that many secondsget(key) β should return None (and delete the key) if it has expiredttl(key) β return remaining seconds, or -1 if no TTL, or -2 if the key is missingThis mirrors how Redis exposes TTL.
Press Run Tests or ββ© to check your solution.