Practical Type Validation
Type Validation Strategies
graph TD
A[Type Validation] --> B[Runtime Checks]
A --> C[Static Type Checking]
A --> D[Custom Validation]
Runtime Type Checking Methods
Using isinstance() Function
def validate_input(value, expected_type):
if not isinstance(value, expected_type):
raise TypeError(f"Expected {expected_type}, got {type(value)}")
def process_data(data: int) -> int:
validate_input(data, int)
return data * 2
Type Validation Decorators
def type_check(func):
def wrapper(*args, **kwargs):
## Extract type hints
annotations = func.__annotations__
## Check argument types
for name, value in list(kwargs.items()) + list(zip(func.__code__.co_varnames, args)):
if name in annotations:
expected_type = annotations[name]
if not isinstance(value, expected_type):
raise TypeError(f"{name} must be {expected_type}")
return func(*args, **kwargs)
return wrapper
@type_check
def create_user(name: str, age: int):
return f"User {name} is {age} years old"
Validation Techniques Comparison
Technique |
Pros |
Cons |
isinstance() |
Simple, built-in |
Manual implementation |
Decorators |
Reusable |
Performance overhead |
Type Guards |
Precise |
Requires careful implementation |
Advanced Validation Patterns
Complex Type Validation
from typing import List, Union
def validate_complex_type(value: Union[List[int], str]):
if isinstance(value, list):
## Validate list of integers
if not all(isinstance(item, int) for item in value):
raise TypeError("List must contain only integers")
elif isinstance(value, str):
## Validate string length
if len(value) > 50:
raise ValueError("String too long")
else:
raise TypeError("Invalid input type")
## Usage examples
validate_complex_type([1, 2, 3]) ## Valid
validate_complex_type("Short string") ## Valid
## validate_complex_type([1, 'a', 3]) ## Raises TypeError
Third-Party Type Validation Libraries
Pydantic for Advanced Validation
from pydantic import BaseModel, validator
class User(BaseModel):
name: str
age: int
@validator('age')
def validate_age(cls, v):
if v < 0:
raise ValueError('Age must be positive')
return v
## Create and validate user
try:
user = User(name="John", age=30)
print(user)
except ValueError as e:
print(f"Validation error: {e}")
LabEx Best Practices
At LabEx, we recommend:
- Combining type hints with runtime validation
- Using type checking tools like mypy
- Implementing custom validation for complex scenarios
graph LR
A[Type Validation] --> B{Performance Impact}
B --> |Light| C[Minimal Overhead]
B --> |Heavy| D[Significant Slowdown]
C --> E[Recommended Approach]
Key Takeaways
- Multiple approaches exist for type validation
- Runtime checks complement static type hints
- Choose validation method based on specific requirements
- Balance between type safety and performance is crucial