Validation Techniques
Understanding Code Validation
Code validation is the process of ensuring that your Python code meets specific criteria, handles inputs correctly, and performs as expected.
Types of Validation Techniques
1. Type Checking
def validate_input(value: int) -> bool:
"""
Validate input type using type hints and isinstance()
Args:
value (int): Input to be validated
Returns:
bool: True if input is valid, False otherwise
"""
if not isinstance(value, int):
raise TypeError("Input must be an integer")
return True
def validate_age(age: int) -> bool:
"""
Validate age range
Args:
age (int): Age to be validated
Returns:
bool: True if age is valid, False otherwise
"""
try:
if 0 < age < 120:
return True
raise ValueError("Age must be between 0 and 120")
except ValueError as e:
print(f"Validation Error: {e}")
return False
Validation Workflow
graph TD
A[Receive Input] --> B{Input Validation}
B -->|Valid| C[Process Data]
B -->|Invalid| D[Raise/Handle Error]
D --> E[Request New Input]
Validation Strategies
Strategy |
Description |
Example |
Type Checking |
Verify input data type |
isinstance(value, int) |
Range Validation |
Check input within acceptable range |
0 < value < 100 |
Regex Validation |
Match input against pattern |
re.match(pattern, input) |
Custom Validation |
Implement specific business logic |
Custom validation functions |
Advanced Validation Techniques
Data Validation with Decorators
def validate_parameters(func):
def wrapper(*args, **kwargs):
for arg in args:
if not isinstance(arg, (int, float)):
raise TypeError("All arguments must be numeric")
return func(*args, **kwargs)
return wrapper
@validate_parameters
def calculate_average(*numbers):
return sum(numbers) / len(numbers)
Using Validation Libraries
## Install popular validation libraries
pip3 install pydantic
pip3 install marshmallow
LabEx Validation Best Practices
- Always validate user inputs
- Use type hints
- Implement comprehensive error handling
- Create reusable validation functions
- Use validation libraries when appropriate
Error Handling Example
class ValidationError(Exception):
"""Custom exception for validation errors"""
pass
def process_user_data(name: str, age: int):
try:
if not name:
raise ValidationError("Name cannot be empty")
if age < 18:
raise ValidationError("User must be 18 or older")
## Process valid data
print(f"Processing data for {name}, {age} years old")
except ValidationError as e:
print(f"Validation Failed: {e}")
Key Takeaways
- Validation prevents unexpected errors
- Use multiple validation techniques
- Create clear, descriptive error messages
- Balance between strict and flexible validation