TypeError
PythonERRORNotableType ErrorHIGH confidence

Operation applied to object of wrong type

What this means

Raised when an operation or function is applied to an object of an inappropriate type. This means the object does not support the attempted operation.

Why it happens
  1. 1Performing an operation between two incompatible types, like adding a string to an integer.
  2. 2Calling a function with an argument of a type it does not expect.
  3. 3Trying to iterate over a non-iterable object, like an integer.
How to reproduce

This error occurs when you try to concatenate a string and a number directly, which is not a supported operation.

trigger — this will error
trigger — this will error
# Attempting to add a string and an integer
result = "hello" + 42

expected output

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

Fix 1

Explicitly convert types before the operation

WHEN When you need to combine values of different types.

Explicitly convert types before the operation
# Convert the integer to a string before concatenation
result = "hello" + str(42)  # "hello42"

Why this works

`str()` converts the integer to its string representation, making concatenation possible.

Fix 2

Use f-string formatting

WHEN When building strings from mixed types, which is a cleaner and more readable approach.

Use f-string formatting
# Use an f-string to embed the integer in the string
num = 42
result = f"hello{num}"  # "hello42"

Why this works

F-strings automatically handle the conversion of embedded expressions to strings.

Code examples
Triggerpython
result = "hello" + 42  # TypeError: can only concatenate str to str
Handle with try/exceptpython
try:
    result = "count: " + count
except TypeError:
    result = f"count: {count}"
Avoid with explicit type checkspython
def greet(name: str) -> str:
    if not isinstance(name, str):
        raise TypeError(f"name must be str, got {type(name).__name__}")
    return f"Hello, {name}"
What not to do

Catch `TypeError` and silently `pass`

This can hide underlying bugs in your data or logic. It's better to handle type conversions explicitly so the code's intent is clear.

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors