Errors/Python

Common Python Errors

Python runtime errors including TypeError, AttributeError, ImportError, KeyError, and async/await issues.

120 errors documented with step-by-step fixes

TypeError: Object is Not Callable

TypeError: 'int' object is not callable

You are trying to call a non-callable object like an integer or list as if it were a function. This usually happens when you shadow a built-in name with a variable. Rename your variable to avoid conflicting with built-in names.

TypeError: NoneType Object is Not Callable

TypeError: 'NoneType' object is not callable

You are calling a variable that is None as if it were a function. This often happens when a function returns None and you chain a call on its result. Check that the object you are calling is actually a function.

TypeError: Wrong Number of Arguments

TypeError: foo() takes 2 positional arguments but 3 were given

You are passing more or fewer arguments than the function expects. For class methods, remember that self counts as the first argument. Check the function signature and match the argument count.

TypeError: Missing Required Positional Argument

TypeError: __init__() missing 1 required positional argument: 'name'

You called a function or class constructor without providing all required arguments. Check the function signature for required parameters and supply them.

TypeError: Unexpected Keyword Argument

TypeError: foo() got an unexpected keyword argument 'bar'

You passed a keyword argument the function does not accept. Check the function signature for valid parameter names or add **kwargs to accept arbitrary keywords.

TypeError: Unsupported Operand Types

TypeError: unsupported operand type(s) for +: 'int' and 'str'

You are trying to use an operator between incompatible types, like adding an integer to a string. Convert one operand to match the other type before performing the operation.

TypeError: Object is Not Iterable

TypeError: 'int' object is not iterable

You are trying to iterate over something that is not iterable, like an integer or NoneType. Ensure you are looping over a list, tuple, string, or other iterable, not a scalar value.

TypeError: Object is Not Subscriptable

TypeError: 'NoneType' object is not subscriptable

You are trying to use square bracket indexing on an object that does not support it, such as None or an integer. This usually means a function returned None when you expected a list or dict.

TypeError: String Indices Must Be Integers

TypeError: string indices must be integers, not 'str'

You are using a string as an index on another string, which means you likely have a string where you expected a dictionary. This often happens when iterating over a JSON string instead of parsed data.

TypeError: Unhashable Type 'list'

TypeError: unhashable type: 'list'

You are trying to use a list as a dictionary key or set element. Lists are mutable and cannot be hashed. Convert the list to a tuple, which is immutable and hashable.

TypeError: Unhashable Type 'dict'

TypeError: unhashable type: 'dict'

You are trying to use a dictionary as a set element or dictionary key. Dicts are mutable and cannot be hashed. Convert to a frozenset of items or use a hashable representation.

TypeError: Cannot Unpack Non-Iterable NoneType

TypeError: cannot unpack non-iterable NoneType object

You are trying to unpack a None value into multiple variables. This happens when a function returns None but you expect it to return a tuple. Fix the function to return values on all code paths.

TypeError: Argument Must Be str, Not bytes

TypeError: a bytes-like object is required, not 'str'

You are mixing str and bytes types. In Python 3, strings are Unicode text and bytes are raw binary data. Encode strings with .encode() or decode bytes with .decode().

TypeError: Method Missing self Parameter

TypeError: greet() takes 0 positional arguments but 1 was given

Your class method is missing the self parameter. When you call obj.method(), Python passes the instance as the first argument automatically, so the method must accept self.

TypeError: Not Enough Arguments for Format String

TypeError: not enough arguments for format string

Your format string has more placeholders than arguments. Use f-strings or .format() for clearer formatting that avoids count mismatches.

AttributeError: NoneType Has No Attribute

AttributeError: 'NoneType' object has no attribute 'append'

You are calling a method on a variable that is None. This means the variable was not assigned properly, or a function returned None when you expected an object. Trace back to find where it became None.

AttributeError: Module Has No Attribute

AttributeError: module 'os' has no attribute 'listdirs'

You are accessing a name that does not exist on the module. This is usually a typo or using the wrong module. Check the module docs for the correct name.

AttributeError: str Has No Attribute

AttributeError: 'str' object has no attribute 'append'

You are calling a method that does not exist on strings. Strings are immutable and do not have list methods like append. Use string concatenation or the appropriate string method.

AttributeError: dict Has No Attribute

AttributeError: 'dict' object has no attribute 'name'

You are using dot notation to access a dictionary key. Dictionaries require bracket notation. Use dict['key'] instead of dict.key.

AttributeError: Object Missing Instance Attribute

AttributeError: 'MyClass' object has no attribute 'value'

You are accessing an attribute that was never set on the instance. Make sure the attribute is initialized in __init__ with self.attribute, not just a local variable.

AttributeError: Partially Initialized Module (Circular Import)

AttributeError: partially initialized module 'json' has no attribute 'loads' (most likely due to a circular import)

You have a file with the same name as a standard library module, causing a circular import. Rename your file so it does not shadow the built-in module.

AttributeError: DataFrame Has No Attribute 'append'

AttributeError: 'DataFrame' object has no attribute 'append'

DataFrame.append() was removed in pandas 2.0. Use pd.concat() instead to combine DataFrames.

AttributeError: __enter__ Not Defined

AttributeError: __enter__

You are using an object with 'with' that does not support context management. The object must implement __enter__ and __exit__ methods. Use contextlib or implement the protocol.

ModuleNotFoundError: No Module Named

ModuleNotFoundError: No module named 'requests'

The module is not installed in your current Python environment. Install it with pip install <module_name>, and make sure you are using the correct virtual environment.

ImportError: Cannot Import Name

ImportError: cannot import name 'foo' from 'bar'

The name you are importing does not exist in the specified module. Check for typos, version mismatches, or circular imports.

ImportError: Circular Import

ImportError: cannot import name 'B' from partially initialized module 'b' (most likely due to a circular import)

Two modules are importing each other, creating a circular dependency. Break the cycle by moving the import inside the function that needs it, or restructure your code.

ImportError: Attempted Relative Import Beyond Top-Level

ImportError: attempted relative import beyond top-level package

You are using a relative import in a script that is not part of a package. Either run the script as a module with python -m, or use an absolute import.

ImportError: DLL Load Failed

ImportError: DLL load failed while importing _ssl: The specified module could not be found.

A compiled extension module cannot find its required shared library. Reinstall the package or install the missing system library.

ModuleNotFoundError: Relative Import in Non-Package

ModuleNotFoundError: No module named '__main__.utils'; '__main__' is not a package

You are using a relative import in a script run directly. Relative imports only work in packages. Run as a module with python -m or use absolute imports.

Externally Managed Environment Error

error: externally-managed-environment

Your system Python does not allow direct pip installs. Use a virtual environment (python -m venv) or pipx for CLI tools.

KeyError: Missing Dictionary Key

KeyError: 'username'

You are accessing a dictionary key that does not exist. Use dict.get('key', default) for safe access, or check with 'key' in dict before accessing.

KeyError in Pandas DataFrame

KeyError: 'column_name'

The column does not exist in the DataFrame. Check for typos, extra whitespace, or case mismatches. Use df.columns.tolist() to see all column names.

KeyError: Missing Environment Variable

KeyError: 'DATABASE_URL'

You are accessing an unset environment variable with os.environ['KEY']. Use os.environ.get('KEY', 'default') for safe access or set the variable before running.

IndexError: List Index Out of Range

IndexError: list index out of range

You are accessing an index that does not exist. The list is shorter than expected. Check length with len() before accessing by index.

IndexError: String Index Out of Range

IndexError: string index out of range

You are accessing a character position that does not exist. Use slicing which gracefully handles out-of-range boundaries, or check string length first.

IndexError: Tuple Index Out of Range

IndexError: tuple index out of range

You are accessing a tuple index that does not exist. Check the tuple length. This often happens with database rows or function return values with fewer elements than expected.

IndexError: Pop from Empty List

IndexError: pop from empty list

You are calling .pop() on an empty list. Check if the list has elements before popping, or use a try/except block.

ValueError: Invalid Literal for int()

ValueError: invalid literal for int() with base 10: 'abc'

You are converting a string to integer but the string is not a valid number. Clean the input or validate before converting.

ValueError: Could Not Convert String to Float

ValueError: could not convert string to float: 'N/A'

You are converting a non-numeric string to float. Handle values like 'N/A', empty strings, or currency symbols before converting.

ValueError: Too Many Values to Unpack

ValueError: too many values to unpack (expected 2)

You are unpacking an iterable into fewer variables than it has elements. Add more variables or use * to capture the rest.

ValueError: Not Enough Values to Unpack

ValueError: not enough values to unpack (expected 3, got 2)

You are unpacking into more variables than the iterable has elements. Check the length before unpacking or provide defaults.

ValueError: Substring Not Found

ValueError: substring not found

You called str.index() with a substring that does not exist. Use str.find() which returns -1 instead, or check with 'in' first.

ValueError: list.remove(x) Not in List

ValueError: list.remove(x): x not in list

You are removing an element that does not exist in the list. Check with 'in' before calling remove(), or use try/except.

ValueError: Math Domain Error

ValueError: math domain error

You passed an invalid value to a math function, such as sqrt of a negative number or log of zero. Validate inputs before calling math functions.

FileNotFoundError: No Such File or Directory

FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'

The file path does not exist. This is usually a relative path issue. Use absolute paths or pathlib.Path to build paths relative to the script location.

PermissionError: Permission Denied

PermissionError: [Errno 13] Permission denied: '/etc/config'

Your process does not have permission to access the file. Check file permissions, run with appropriate privileges, or write to a user directory instead.

OSError: Too Many Open Files

OSError: [Errno 24] Too many open files

Your process exceeded the OS limit on open file descriptors. Close files properly using 'with' statements, or increase the limit.

OSError: No Space Left on Device

OSError: [Errno 28] No space left on device

The disk is full. Free up space by deleting temporary files or logs. Use log rotation to prevent unbounded growth.

IsADirectoryError: Path is a Directory

IsADirectoryError: [Errno 21] Is a directory: '/tmp/data'

You are trying to open a directory as a file. Check your path to make sure it includes the filename, not just the directory.

UnicodeDecodeError: Invalid Start Byte

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

The file is not encoded in UTF-8 as Python assumes. Specify the correct encoding when opening the file, or use a library like chardet to detect it.

UnicodeEncodeError: Character Cannot Be Encoded

UnicodeEncodeError: 'ascii' codec can't encode character

You are encoding a Unicode string with an encoding that cannot represent all characters. Use UTF-8 encoding which supports all Unicode characters.

FileNotFoundError in subprocess: Command Not Found

FileNotFoundError: [Errno 2] No such file or directory: 'my-command'

The command you are running with subprocess does not exist or is not on the PATH. Verify installation, use full path, or check with shutil.which().

RecursionError: Maximum Recursion Depth Exceeded

RecursionError: maximum recursion depth exceeded in comparison

Your function calls itself too many times without reaching a base case. Add or fix the base case, or convert to an iterative approach.

RecursionError in __repr__ or __str__

RecursionError: maximum recursion depth exceeded while calling a Python object

Your __repr__ or __str__ method causes infinite recursion through circular references. Break the cycle by only showing identifiers, not full nested representations.

MemoryError: Out of Memory

MemoryError

Your program tried to allocate more memory than available. Use generators, chunked reading, or memory-efficient data structures.

MemoryError: Creating Large List

MemoryError

You are creating a list too large to fit in memory. Use range() directly for iteration or generator expressions for lazy evaluation.

ZeroDivisionError: Division by Zero

ZeroDivisionError: division by zero

You are dividing by zero. Add a check to ensure the divisor is not zero before performing the division.

RuntimeError: Event Loop Already Running

RuntimeError: This event loop is already running

You are calling asyncio.run() from inside an already running event loop. In Jupyter notebooks, use 'await' directly. In other contexts, use asyncio.create_task().

RuntimeWarning: Coroutine Was Never Awaited

RuntimeWarning: coroutine 'fetch_data' was never awaited

You called an async function without 'await', so it returned a coroutine object instead of executing. Add 'await' before the call.

RuntimeError: No Running Event Loop

RuntimeError: no running event loop

You are using an asyncio feature that requires a running event loop, but none is active. Use asyncio.run() to start one.

asyncio.TimeoutError: Operation Timed Out

asyncio.TimeoutError

An async operation exceeded the specified timeout. Increase the timeout or investigate why the operation is slow.

asyncio.CancelledError: Task Was Cancelled

asyncio.CancelledError

An asyncio task was cancelled while running. Handle CancelledError for cleanup, but always re-raise it so cancellation completes.

Task Exception Was Never Retrieved

Task exception was never retrieved: future: <Task finished ... exception=ValueError('...')>

An asyncio task raised an exception but you never awaited it. Always await tasks or call task.result() to retrieve exceptions.

Blocking Call in Async Context

Event loop is blocked by synchronous code

You are calling a blocking function inside async code, which freezes the event loop. Use asyncio.to_thread() or async libraries instead.

SyntaxError: await Outside Async Function

SyntaxError: 'await' outside function

You are using await outside of an async function. Wrap your code in an async def function and run it with asyncio.run().

TypeError: Object Cannot Be Used in Await

TypeError: object NoneType can't be used in 'await' expression

You are awaiting a non-awaitable object. Only coroutines, Tasks, and Futures can be awaited. Check that the function is defined with async def.

JSONDecodeError: Invalid JSON

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The string is not valid JSON. Common causes include empty strings, HTML error pages, single quotes, and trailing commas. Validate the string before parsing.

TypeError: Object Not JSON Serializable

TypeError: Object of type datetime is not JSON serializable

You are serializing an object JSON does not support natively, like datetime, set, or bytes. Convert to a supported type or provide a custom encoder.

JSONDecodeError: Extra Data

json.decoder.JSONDecodeError: Extra data: line 2 column 1

Your string contains multiple JSON values concatenated. Parse each line separately for NDJSON, or ensure you have a single valid JSON document.

ValueError: Circular Reference in JSON

ValueError: Circular reference detected

Your data has a circular reference. JSON cannot represent cycles. Remove the cycle or use a custom serializer.

TypeError: Bytes Object Not JSON Serializable

TypeError: Object of type bytes is not JSON serializable

You have bytes data that needs conversion before JSON serialization. Decode text bytes with .decode() or base64-encode binary data.

UnpicklingError: Could Not Load Pickle

pickle.UnpicklingError: could not find MARK

The pickle file is corrupted, truncated, or created with an incompatible protocol. Regenerate it from original data. Always use binary mode ('rb'/'wb') for pickle files.

YAML Scanner Error: Invalid YAML

yaml.scanner.ScannerError: while scanning a simple key

Your YAML has a syntax error like tabs instead of spaces or unquoted special characters. YAML requires spaces for indentation.

NameError: Name is Not Defined

NameError: name 'result' is not defined

You are using a variable that has not been defined. Check for typos, make sure it is defined before use, and verify scope.

UnboundLocalError: Referenced Before Assignment

UnboundLocalError: local variable 'count' referenced before assignment

You are reading a variable before assigning it in the same function. Python sees the assignment and treats it as local for the entire function. Use global or nonlocal if modifying an outer variable.

SyntaxError: Invalid Syntax

SyntaxError: invalid syntax

Your code has a syntax error. Common causes include missing colons after if/for/def, unmatched parentheses, and using = instead of ==.

SyntaxError: Unexpected Indent

IndentationError: unexpected indent

Your code has incorrect indentation. Python uses indentation for code blocks. Use consistent 4-space indentation and do not mix tabs and spaces.

SyntaxError: EOL While Scanning String Literal

SyntaxError: EOL while scanning string literal

You have an unclosed string literal. Check for missing closing quotes. For multi-line strings, use triple quotes.

StopIteration: Iterator Exhausted

StopIteration

You called next() on an empty or exhausted iterator. Use next(iter, default) to provide a default value, or use a for loop which handles StopIteration automatically.

AssertionError: Assertion Failed

AssertionError

An assert statement evaluated to False. Use proper exceptions for input validation instead of assert, which can be disabled with python -O.

RuntimeError: Dictionary Changed Size During Iteration

RuntimeError: dictionary changed size during iteration

You are modifying a dictionary while iterating over it. Create a copy of keys to iterate over, or collect changes and apply after the loop.

ValueError: Time Data Does Not Match Format

ValueError: time data '2024-01-15' does not match format '%m/%d/%Y'

The datetime string format does not match your format string. Check strptime format codes and match them exactly to the date string structure.

TypeError: Cannot Compare Naive and Aware Datetimes

TypeError: can't compare offset-naive and offset-aware datetimes

You are comparing a datetime with timezone info to one without. Make both timezone-aware or both naive. Use datetime.now(timezone.utc) for aware datetimes.

re.error: Bad Escape Sequence

DeprecationWarning: invalid escape sequence '\d'

You have an invalid escape sequence in a regular string. Use raw strings (r'...') for regex patterns so Python does not interpret backslashes.

re.error: Unterminated Subpattern

re.error: missing ), unterminated subpattern at position 0

Your regex has unmatched parentheses. Check that every opening parenthesis has a closing one, or escape literal parentheses with backslashes.

ConnectionRefusedError: Connection Refused

ConnectionRefusedError: [Errno 111] Connection refused

The server is not accepting connections. Check that it is running, the host and port are correct, and no firewall is blocking.

ConnectionError: Connection Timed Out

requests.exceptions.ConnectTimeout: Max retries exceeded (connect timeout)

The server did not respond in time. Increase timeout, add retries with backoff, or check network connectivity.

SSLCertVerifyError: Certificate Verify Failed

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED]

SSL certificate verification failed. The certificate may be expired, self-signed, or the CA bundle outdated. Fix the certificate rather than disabling verification.

NotImplementedError: Abstract Method

NotImplementedError

You are calling a method meant to be overridden by a subclass. Implement the method in your subclass.

PicklingError: Cannot Pickle Lambda or Local Function

AttributeError: Can't pickle local object

Multiprocessing needs to serialize functions to send to workers, but lambdas and local functions cannot be pickled. Define functions at module level.

OSError: Address Already in Use

OSError: [Errno 98] Address already in use

Another process is listening on the same port. Find and stop it, use a different port, or set SO_REUSEADDR.

Environment Variables Not Loaded from .env

KeyError: 'SECRET_KEY' (variable in .env but not loaded)

Your .env file is not loaded automatically. Install python-dotenv and call load_dotenv() before accessing environment variables.

NameError: Forward Reference in Type Hint

NameError: name 'MyClass' is not defined

You are using a type hint that references a class not yet defined. Use string literals or add 'from __future__ import annotations'.

os.path.join Ignoring First Argument

os.path.join returns only the second argument when it starts with /

os.path.join() discards all previous components when it encounters an absolute path. Remove the leading slash from the second argument.

Pydantic ValidationError: Invalid Data

pydantic.ValidationError: 1 validation error for User

The data does not match the Pydantic model schema. Check error details for which fields failed and fix the input data.

SQLAlchemy DetachedInstanceError

sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session

You are accessing a lazy-loaded relationship after the session closed. Use eager loading or access data while the session is open.

ImproperlyConfigured: Django Settings Not Configured

django.core.exceptions.ImproperlyConfigured: Requested setting but settings are not configured.

Django settings are not configured. Set DJANGO_SETTINGS_MODULE and call django.setup() before importing Django modules.

RuntimeError: Working Outside of Application Context

RuntimeError: Working outside of application context.

You are using Flask features outside a request or app context. Use app.app_context() to create a context manually.

MissingSchema: Invalid URL

requests.exceptions.MissingSchema: Invalid URL: No schema supplied.

The URL is missing the protocol scheme (http:// or https://). Add the full scheme to the URL.

MaxRetryError: Maximum Retries Exceeded

urllib3.exceptions.MaxRetryError: Max retries exceeded

The HTTP request failed after all retry attempts. Check the 'Caused by' section for the root cause (DNS, SSL, timeout).

httpx.ReadTimeout: Read Operation Timed Out

httpx.ReadTimeout: timed out

The server took too long to send the response. Increase the read timeout or investigate server performance.

sqlite3.OperationalError: Database is Locked

sqlite3.OperationalError: database is locked

Another connection has a write lock on the SQLite database. Use WAL mode, close other connections, or switch to a client-server database.

csv.Error: Iterator Should Return Strings

iterator should return strings, not bytes (did you open the file in text mode?)

You opened the CSV file in binary mode ('rb') but csv expects text mode. Open with mode='r' and specify encoding.

FrozenInstanceError: Cannot Assign to Field

dataclasses.FrozenInstanceError: cannot assign to field 'name'

You are modifying a frozen dataclass which is immutable. Use dataclasses.replace() to create a modified copy.

ValueError: Invalid Enum Value

ValueError: 'invalid' is not a valid Color

You are creating an enum member with a value that does not exist. Use try/except or check membership before creating enum instances.

LookupError: Unknown Encoding

LookupError: unknown encoding: utf8mb4

The encoding name is not recognized by Python. Check against Python's standard encoding names. MySQL utf8mb4 is Python utf-8.

struct.error: Unpack Requires Buffer of Size

struct.error: unpack requires a buffer of 4 bytes

The binary data does not match the expected size for the format string. Check data length matches what the format expects.

OverflowError: int Too Large to Convert

OverflowError: int too large to convert to float

The integer is too large for float representation (max ~1.8e308). Use the decimal module or integer arithmetic.

BrokenProcessPool: Process Pool Not Running

concurrent.futures.process.BrokenProcessPool: A child process terminated abruptly

A worker process crashed. Handle exceptions inside worker functions and consider ThreadPoolExecutor for I/O-bound work.

SyntaxError: Walrus Operator in Wrong Context

SyntaxError: cannot use assignment expressions with variable

You are using the walrus operator (:=) incorrectly. It is for inline assignment in expressions like while loops and if conditions, not as a replacement for regular assignment.

TypeError: Cannot Use Path with Legacy Function

TypeError: expected str, bytes or os.PathLike object, not PosixPath

The function does not accept pathlib.Path objects. Convert with str(path). Most stdlib functions support Path since Python 3.6.

No Handlers Could Be Found for Logger

No handlers could be found for logger 'myapp'

The logger has no handlers configured. Call logging.basicConfig() or add handlers to your logger.

TypeError: Expected String or Bytes-Like Object

TypeError: expected string or bytes-like object, got 'NoneType'

You passed None to a function expecting a string, like re.match() or str methods. Check that your variable is not None first.

RuntimeError: Generator Raised StopIteration

RuntimeError: generator raised StopIteration

A StopIteration was raised inside a generator, which Python 3.7+ converts to RuntimeError. Use return instead of raise StopIteration, or catch StopIteration inside the generator.

EOFError: End of File When Reading Input

EOFError: EOF when reading a line

input() reached end of file with no data. This happens when running scripts non-interactively (piped input, automated tests) and there is no input to read.

BrokenPipeError: Broken Pipe

BrokenPipeError: [Errno 32] Broken pipe

The receiving end of a pipe was closed while you were writing. This commonly happens when piping Python output to head or grep and the reader closes early. Handle the signal or catch the error.

TypeError: Cannot Subtract date from datetime

TypeError: unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'

You are mixing datetime.date and datetime.datetime objects. Convert one to match the other using .date() or datetime.combine().

TypeError: super().__init__() Missing Arguments

TypeError: __init__() missing 1 required positional argument: 'message'

Your subclass is not passing required arguments to the parent __init__. Make sure super().__init__() receives all arguments the parent class expects.

RuntimeError: Set Changed Size During Iteration

RuntimeError: Set changed size during iteration

You are modifying a set while iterating over it. Copy the set before iterating or collect changes to apply afterward.

re.error: Nothing to Repeat

re.error: nothing to repeat at position 0

You have a quantifier (*, +, ?) at the start of a pattern or after another quantifier. Quantifiers must follow a character or group to repeat.

Bugsly catches Python errors automatically

AI-powered error tracking that explains what went wrong and suggests fixes. Set up in 2 minutes.

Get Started Free