Skip to main content

Cache.add()

Store value only if key is missing or expired.

Usage

Source

Cache.add(
    key,
    value,
    expire=None,
    *,
    tag=None,
    retry=False,
)

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: Key

The key.

value: Any

The value, as for set().

expire: Optional[float] = None

Seconds until the entry expires, or None for never.

tag: Key = None

The entry’s tag, as for set(). A live entry keeps its own.

retry: bool = False
On a Timeout, try again until the call gets through, each round with the whole timeout, a durable=True handle included. Only Timeout is retried.

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.

UnicodeEncodeError

The value is a str with a lone surrogate, or holds one and the cache has no pickle.

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