How to Validate Input and Raise TypeError in Python
Define a function that checks its argument type and raises a TypeError early with a clear message when given a non-number.
Python code
11 linesdef validate_number(value):
if not isinstance(value, (int, float)):
raise TypeError(f"Expected a number, got {type(value).__name__}")
return value * 2
if __name__ == "__main__":
try:
print(validate_number(5))
print(validate_number("hello"))
except TypeError as e:
print(f"Error: {e}")
Output
10
Error: Expected a number, got str
How it works
The isinstance check ensures only int or float values are accepted; otherwise a TypeError is raised with a descriptive message that includes the actual type name. By raising the error early, you avoid confusing downstream failures. The try/except block in the main guard demonstrates how to catch and handle the error gracefully.
Common mistakes
- Using `type(value) == int` which fails for subclasses or boolean values
- Raising a generic `ValueError` instead of the specific `TypeError`
- Checking `isinstance(value, (int, float))` but forgetting `bool` is a subclass of `int`
- Not including the actual type in the error message
Variations
- Use Python 3.10+ with `match value:` to validate type patterns
- Use a type annotation like `def validate_number(value: int) -> int:` combined with a runtime check
Real-world use cases
- Validating user input before performing arithmetic in a CLI calculator script.
- Checking configuration parameters at service startup to fail fast with clear errors.
- Ensuring numeric fields in API request handlers are the correct type before processing.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.