LookupError
LookupError
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
return container[key] # may raise IndexError or KeyError
LookupErrorWhat causes this error
An index or key lookup failed. This is the base class for IndexError and KeyError and is not usually raised directly.
How to fix it
Catch LookupError when you want to handle both IndexError and KeyError. Use `.get()` for dicts and bounds checking for sequences. Prefer specific exception types when you know the data structure.
Code that causes this error
def get_item(container, key):
return container[key] # may raise IndexError or KeyErrorFixed code
def get_item(container, key, default=None):
try:
return container[key]
except LookupError:
return defaultAbout LookupError
LookupError is the base class for exceptions raised when a key or index is invalid. It is the parent of both KeyError and IndexError. You typically do not see LookupError raised directly — instead, you encounter its subclasses.
However, catching LookupError in an except clause is useful when you want to handle both KeyError and IndexError with the same code. This is particularly handy in generic code that works with both sequences and mappings, where you want to catch any failed lookup regardless of the container type. Some third-party libraries and ORMs also raise LookupError subclasses for not-found conditions.
The LookupError class itself is primarily an organizational hierarchy marker in Python's exception taxonomy.
Common scenarios
Infinite recursion from missing or incorrect base cases
Modifying dictionaries or sets during iteration
Calling generators or coroutines in unsupported ways
Using asyncio event loops incorrectly or attempting to nest them