redis/redis-py · error · KeyError
{name}
Error message
{name} What it means
The bracket-access operator r[name] (CoreCommands.__getitem__) calls get() and raises KeyError(name) when the key is absent. This mirrors dict semantics so client['foo'] fails fast on missing keys instead of returning None. The exception's message/arg is the key name itself.
Source
Thrown at redis/commands/core.py:3303
"and ``persist`` are mutually exclusive."
)
exp_options: list[EncodableT] = extract_expire_flags(ex, px, exat, pxat)
if persist:
exp_options.append("PERSIST")
return self.execute_command("GETEX", name, *exp_options)
def __getitem__(self, name: KeyT):
"""
Return the value at key ``name``, raises a KeyError if the key
doesn't exist.
"""
value = self.get(name)
if value is not None:
return value
raise KeyError(name)
@overload
def getbit(self: SyncClientProtocol, name: KeyT, offset: int) -> int: ...
@overload
def getbit(
self: AsyncClientProtocol, name: KeyT, offset: int
) -> Awaitable[int]: ...
def getbit(self, name: KeyT, offset: int) -> int | Awaitable[int]:
"""
Returns an integer indicating the value of ``offset`` in ``name``
For more information, see https://redis.io/commands/getbit
"""
return self.execute_command("GETBIT", name, offset, keys=[name])
@overloadView on GitHub (pinned to da03cdc7e8)
Solutions
- Use r.get('key') which returns None for missing keys if that is the desired semantics.
- Check existence first with r.exists('key') when you need to branch on presence.
- Catch KeyError around bracket access if absence is a normal, recoverable case.
Example fix
# before
val = r['maybe_missing'] # raises KeyError if absent
# after
val = r.get('maybe_missing') # None if absent
# or explicit presence check:
if r.exists('maybe_missing'):
val = r['maybe_missing'] Defensive patterns
Strategy: try-catch
Validate before calling
# Prefer get() to avoid the exception entirely:
val = r.get('maybe_missing')
if val is None:
... # handle absence without raising Type guard
def key_exists(client, key) -> bool:
return bool(client.exists(key)) Try / catch
try:
val = r['maybe_missing']
except KeyError:
val = None # or your default Prevention
- Use r.get(key) when absence is normal; reserve bracket access for when missing keys are a bug.
- Check r.exists(key) before bracket access in conditional flows.
When it happens
Trigger: r['missing_key'] where the key does not exist in Redis. Returns the value only when the key is present; otherwise raises KeyError with the key as the argument.
Common situations: Treating the Redis client like a dict in templating or config code; assuming a key was written earlier in the same flow; using bracket access in a hot loop without existence checks.
Related errors
- Maintenance notifications handlers on connection are only su
- MONITOR failed: {response}
- pubsub connection not set: did you forget to call subscribe(
- Channel: '{channel}' has no handler registered
- Pattern: '{pattern}' has no handler registered
AI-assisted analysis of redis/redis-py@da03cdc7e8 (2026-08-04).
Data as JSON: /data/errors/9e4929051ae2235e.json.
Report an issue: GitHub.