🐍 Python errors

Python exceptions: ImportError, KeyError, TypeError, IndentationError and more.

CodeErrorWhat it means
AttributeError AttributeError: 'X' object has no attribute 'y' You accessed an attribute or method that doesn’t exist on that object type.
numpy alias removed AttributeError: module 'numpy' has no attribute 'float' Code uses np.float/np.int/np.bool/np.object, which were removed in NumPy 1.24.
ConnectionRefusedError ConnectionRefusedError: [Errno 111] Connection refused Nothing is listening on the host/port Python tried to connect to.
DisallowedHost django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'x'. You may need to add 'x' to ALLOWED_HOSTS. The request’s Host header isn’t listed in Django’s ALLOWED_HOSTS.
ImproperlyConfigured django.core.exceptions.ImproperlyConfigured: settings are not configured / SECRET_KEY must not be empty Django can’t load its settings — DJANGO_SETTINGS_MODULE unset, a required setting missing, or an environment…
Django no such table django.db.utils.OperationalError: no such table: app_model Django queried a table that hasn’t been created — migrations missing or not applied.
TemplateDoesNotExist django.template.exceptions.TemplateDoesNotExist: app/page.html Django searched all template directories and couldn’t find that template.
pip no matching distribution ERROR: Could not find a version that satisfies the requirement x (from versions: none) pip found no installable version of the package for your Python version, OS or index.
externally-managed-environment error: externally-managed-environment Your system Python (Debian 12+, Ubuntu 23.04+, Homebrew) refuses pip installs into the OS-managed environment…
Failed building wheel error: subprocess-exited-with-error / Failed building wheel for x pip had to compile a package from source and the build failed — missing compiler, headers or system libraries.
FileNotFoundError FileNotFoundError: [Errno 2] No such file or directory: 'data.csv' Python couldn’t find the file at that path — usually because relative paths resolve from the working director…
Django CSRF Forbidden (403) CSRF verification failed. Request aborted. Django rejected a POST because the CSRF token was missing, wrong, or the request origin isn’t trusted.
ImportError ImportError: cannot import name 'x' from 'y' The module was found, but the name you’re importing from it doesn’t exist — usually a version change or a cir…
IndentationError IndentationError: unexpected indent / expected an indented block Python’s block structure is broken — inconsistent indentation or mixed tabs and spaces.
IndexError IndexError: list index out of range Code accessed a list position that doesn’t exist.
JSONDecodeError json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) The text passed to json.loads() isn’t JSON — at char 0 it’s usually empty or HTML.
KeyboardInterrupt KeyboardInterrupt (script stopped with Ctrl+C) / ^C traceback The script was interrupted (Ctrl+C, SIGINT, or a container stop), producing a KeyboardInterrupt traceback.
KeyError KeyError: 'x' You accessed a dictionary key that doesn’t exist.
MemoryError MemoryError (Unable to allocate X GiB for an array) Python couldn’t allocate memory — the data is larger than available RAM or address space.
No module named distutils ModuleNotFoundError: No module named 'distutils' Python 3.12 removed distutils; old packages or tools that import it fail.
ModuleNotFoundError ModuleNotFoundError: No module named 'x' Python can’t find the module you import — it isn’t installed in the interpreter/virtualenv that’s running, or…
NameError NameError: name 'x' is not defined Python doesn’t know the name — it was never assigned/imported in this scope, or it’s misspelled.
OSError Errno 98 OSError: [Errno 98] Address already in use The port your server wants to bind is already taken by another process.
PermissionError PermissionError: [Errno 13] Permission denied: '/path' The OS refused the file operation — no permission, a directory passed to open(), or (on Windows) the file is…
Pydantic ValidationError pydantic_core._pydantic_core.ValidationError: 1 validation error for Model Data didn’t match a Pydantic model — a field is missing, has the wrong type, or fails a constraint.
Python not found Python was not found; run without arguments to install from the Microsoft Store Windows ran the Microsoft Store “App execution alias” instead of a real Python installation.
RecursionError RecursionError: maximum recursion depth exceeded A function called itself (directly or indirectly) more than ~1000 times.
requests ConnectionError requests.exceptions.ConnectionError: HTTPSConnectionPool(host=…, port=443): Max retries exceeded with url requests couldn’t connect — the inner error (NewConnectionError, NameResolutionError, SSLError, ConnectTimeou…
RuntimeError dict RuntimeError: dictionary changed size during iteration A dict (or set) was modified while being looped over.
Event loop is closed RuntimeError: Event loop is closed Async code tried to use an event loop that has already been shut down.
Flask app context RuntimeError: Working outside of application context. Code used current_app, g, or a Flask extension (like SQLAlchemy) without an active Flask application context.
never awaited RuntimeWarning: coroutine 'fetch' was never awaited An async function was called without await, so it never ran.
SettingWithCopyWarning SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame pandas can’t tell whether your assignment modifies the original DataFrame or a temporary copy.
SQLAlchemy IntegrityError sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint A database constraint (unique, foreign key, not null) rejected an insert/update made through SQLAlchemy.
SQLAlchemy OperationalError sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server … failed SQLAlchemy’s DB driver raised an operational error — connection failures, lost connections or locked SQLite d…
SyntaxError SyntaxError: invalid syntax Python couldn’t parse the code. The caret (^) points at or just after the mistake.
Jupyter kernel died The kernel appears to have died. It will restart automatically. The Jupyter kernel process crashed — usually out of memory or a native library crash.
TypeError: NoneType TypeError: 'NoneType' object is not subscriptable You used `[ ]` on a value that is `None` — typically a function that returned nothing.
TypeError not callable TypeError: 'str' object is not callable You used parentheses on something that isn’t a function — often a variable shadowing a built-in.
TypeError concat TypeError: can only concatenate str (not "int") to str You joined a string and a non-string with +.
TypeError missing arg TypeError: f() missing 1 required positional argument: 'x' A function was called without a required parameter.
TypeError arguments TypeError: f() takes 1 positional argument but 2 were given A function was called with more positional arguments than it accepts — very often a method missing `self`.
not JSON serializable TypeError: Object of type datetime is not JSON serializable json.dumps() met a type it doesn’t know how to encode (datetime, Decimal, set, custom objects).
unhashable type TypeError: unhashable type: 'list' A mutable object (list, dict, set) was used as a dict key or set member.
TypeError operand TypeError: unsupported operand type(s) for +: 'int' and 'str' An operator was used between two incompatible types, such as adding a number to a string.
UnboundLocalError UnboundLocalError: cannot access local variable 'x' where it is not associated with a value A function assigns to a variable somewhere, which makes it local everywhere in that function — so reading it…
UnicodeDecodeError UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 10: invalid start byte Python read bytes that aren’t valid in the encoding it assumed (usually UTF-8).
UnicodeEncodeError UnicodeEncodeError: 'charmap' codec can't encode character '\u2192' Python tried to write text in an encoding that can’t represent some characters — common in Windows consoles a…
ValueError ValueError: invalid literal for int() with base 10: 'abc' int() received a string that isn’t a whole number — empty, decimal, whitespace or text.
broadcast error ValueError: operands could not be broadcast together with shapes (3,) (4,) Two NumPy arrays have shapes that can’t be combined element-wise.
ValueError ambiguous truth ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). A pandas Series/NumPy array was used where Python expects a single True/False (if, and, or).
unpack error ValueError: too many values to unpack (expected 2) Tuple unpacking got more (or fewer) values than variables on the left.
ZeroDivisionError ZeroDivisionError: division by zero A number was divided (or modulo’d) by zero.