Python Reference ยท Exceptions
Python TypeError
Reference for Python TypeError: operations on the wrong type, wrong argument counts, unhashable and not-callable objects, and how to fix each common message.
TypeError is raised when an operation or function is applied to an object of an inappropriate type. Adding a number to a string, calling something that is not a function, or passing the wrong number of arguments all produce it.
Python is dynamically typed, so these mistakes appear only when the line runs. The message normally names both the operation and the types involved, which makes it quick to diagnose.
"age: " + 30 # TypeError: can only concatenate str (not "int") to str
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
raise TypeError("message") try: ... except TypeError as error: ...
| Name | Description |
|---|---|
message |
Optional text stored in error.args. |
Raises when: the operand or argument type does not support the operation, or the call signature does not match.
Usage notes
- Common messages and fixes:
unsupported operand type(s) for +orcan only concatenate str: convert withstr(),int()or an f-string.'int' object is not callable: you shadowed a function with a variable (sum = 5) or wrotex(...)on a value.'NoneType' object is not subscriptableor... is not iterable: a function returnedNone(often a mutating method likelist.sort()used asx = x.sort()).unhashable type: 'list': use a tuple orfrozensetfor dict keys and set members.missing 1 required positional argumentandtakes 2 positional arguments but 3 were given: check the signature; for methods,selfcounts in the message.'<' not supported between instances of 'int' and 'str': compare or sort values of one type.
- TypeError vs. ValueError. The wrong kind of object is
TypeError; the right kind with an unacceptable value isValueError. - Return
NotImplemented, notTypeError, from operator methods; Python raises the error if no side can handle it. - Duck typing. Prefer trying the operation and catching
TypeErrorto checkingisinstancein advance, except when you want a friendlier message. - Type hints do not prevent it. Annotations are not enforced at run time; use a checker such as mypy or pyright to find these errors before running.
- Raise it yourself for wrong argument types in your own functions, naming the expected and received types.