Validation Techniques
Overview of Validation Methods
Parameter validation involves multiple techniques to ensure data integrity and prevent errors. This section explores comprehensive strategies for validating function inputs.
1. Type Validation
Built-in Type Checking
def process_data(value):
if not isinstance(value, (int, float, str)):
raise TypeError("Invalid input type")
return value
Type Hints with Validation
from typing import Union
def calculate(x: Union[int, float], y: Union[int, float]) -> float:
if not isinstance(x, (int, float)) or not isinstance(y, (int, float)):
raise TypeError("Numeric inputs required")
return x + y
2. Range Validation
Numeric Range Validation
def set_temperature(temp: float):
if temp < -273.15 or temp > 1000:
raise ValueError("Temperature out of valid range")
return temp
3. Pattern Matching Validation
Regular Expression Validation
import re
def validate_email(email: str):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(pattern, email):
raise ValueError("Invalid email format")
return email
4. Decorator-based Validation
def validate_positive(func):
def wrapper(*args, **kwargs):
for arg in args:
if arg < 0:
raise ValueError("Negative values not allowed")
return func(*args, **kwargs)
return wrapper
@validate_positive
def calculate_square_root(x):
return x ** 0.5
Validation Strategies Comparison
Technique |
Pros |
Cons |
Type Checking |
Simple, Fast |
Limited complexity |
Range Validation |
Precise control |
Requires manual implementation |
Regex Validation |
Complex pattern matching |
Performance overhead |
Decorator Validation |
Reusable, Flexible |
Can complicate code |
Validation Flow
flowchart TD
A[Input Data] --> B{Type Check}
B -->|Pass| C{Range Check}
B -->|Fail| D[Raise Type Error]
C -->|Pass| E{Pattern Check}
C -->|Fail| F[Raise Value Error]
E -->|Pass| G[Process Function]
E -->|Fail| H[Raise Format Error]
Advanced Validation Techniques
- Use third-party libraries like
pydantic
- Implement custom validation classes
- Leverage type annotations
At LabEx, we emphasize creating robust validation mechanisms to ensure code reliability and maintainability.