Operation applied to object of wrong type
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.
- 1Performing an operation between two incompatible types, like adding a string to an integer.
- 2Calling a function with an argument of a type it does not expect.
- 3Trying to iterate over a non-iterable object, like an integer.
This error occurs when you try to concatenate a string and a number directly, which is not a supported operation.
# 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.
# 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 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.
result = "hello" + 42 # TypeError: can only concatenate str to str
try:
result = "count: " + count
except TypeError:
result = f"count: {count}"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}"✕ 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