Skip to main content

Cache.add()

Store value only if key is missing or expired.

Usage

Source

Cache.add(
    key,
    value,
    expire=None,
)

Atomic across threads and processes: when several callers race to add one key, exactly one succeeds. That makes it a simple way to claim a job or take a lock.

Parameters

key: str

The key.

value: Any

The value, as for set().

expire: float | None = None
Seconds until the entry expires, or None for never.

Returns

bool

True if the value was stored, False if the key already held a live value. With

durable=True, also False if the write failed, so a claim fails closed. A NullCache

returns True, so use a non-durable handle for claims and locks.

Raises

TypeError

The value can’t be stored exactly without pickle, or expire is a bool.

Timeout
Another process held the write lock for longer than timeout.

Examples

if cache.add('job:hourly-cleanup', os.getpid(), expire=55 * 60):
    remove_stale_sessions()   # only the worker whose add() returned True gets here