TypeError
TypeError is a built-in exception that occurs when an operation is applied to an object of inappropriate type. For example, trying to add a string to an integer will raise a TypeError because these types implement addition in different and incompatible ways.
You should use this exception to catch and handle errors that occur due to invalid types in your code.
TypeError Occurs When
TypeError Can Be Used When
TypeError Examples
An example of when the exception appears:
Python
>>> len(42)
Traceback (most recent call last):
...
TypeError: object of type 'int' has no len()
>>> "Hello"()
Traceback (most recent call last):
...
TypeError: 'str' object is not callable
An example of how to handle the exception:
Python
>>> def safe_add(a, b):
... try:
... return a + b
... except TypeError:
... print(f"{type(a)} and {type(b)} are incompatible for addition.")
... return None
...
>>> safe_add(5, 10)
15
>>> safe_add(5, "10")
<class 'int'> and <class 'str'> are incompatible for addition.
An example of when you may want to raise the exception:
Python
>>> def run_callback(callback, *args, **kwargs):
... if not callable(callback):
... raise TypeError("callback must be callable")
... return callback(*args, **kwargs)
...
>>> run_callback(42)
Traceback (most recent call last):
...
TypeError: callback must be callable