A TypeError occurs when an operation or function receives an inappropriate type or incompatible argument. It can signal that Python cannot perform the requested operation with the supplied objects. section 3.2 section 12.5.2
Common situations include:
- Sorting a list of dictionaries without specifying which dictionary value should determine the order; Python cannot compare the dictionaries directly. section 3.2
- Passing a non-string title to a Task constructor that requires a string. section 12.5.2
- Assigning a new value to an item in an immutable tuple. section 3.1.1
Raise TypeError for an invalid argument
class Task: def __init__(self, title): if isinstance(title, str): self.title = title else: raise TypeError("Please instantiate the Task using string as its title") task = Task(100) # TypeError: Please instantiate the Task using string as its title section 12.5.2
tasks.sort() # ERROR: TypeError: '<' not supported between instances of 'dict' and 'dict'
Shows the direct failure produced when Python tries to sort dictionaries without a custom comparison key. section 3.2
Prefer the built-in TypeError when rejecting an argument: its meaning is familiar, and callers can handle it with try...except...else...finally. Tests can also raise TypeError deliberately to expose faulty code. section 12.5.2 section 12.5.5

