Practical Type Validation
Comprehensive Generator Type Validation
1. Custom Type Validation Function
import inspect
from typing import Any, Generator, Iterator
def validate_generator(obj: Any) -> bool:
"""
Comprehensive generator validation function
Args:
obj: Object to validate
Returns:
Boolean indicating generator status
"""
return (
inspect.isgenerator(obj) or
inspect.isgeneratorfunction(obj) or
isinstance(obj, Iterator)
)
## Example usage
def sample_generator():
yield from range(5)
gen = sample_generator()
print(validate_generator(gen)) ## True
Type Validation Strategies
2. Runtime Type Checking Decorator
from functools import wraps
from typing import Callable, Generator, Any
def validate_generator_input(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args, **kwargs):
for arg in args:
if not inspect.isgenerator(arg):
raise TypeError(f"Expected generator, got {type(arg)}")
return func(*args, **kwargs)
return wrapper
@validate_generator_input
def process_generator(gen):
return list(gen)
## Safe usage
test_gen = (x for x in range(5))
result = process_generator(test_gen)
Validation Workflow
graph TD
A[Input Object] --> B{Is Generator?}
B --> |Yes| C[Process Normally]
B --> |No| D[Raise Type Error]
D --> E[Handle or Log Error]
Advanced Type Validation Techniques
3. Type Hint Validation with typing
Module
from typing import TypeVar, Generator, Iterator
T = TypeVar('T')
def strict_generator_validation(
gen: Generator[T, None, None] | Iterator[T]
) -> list[T]:
"""
Strictly validate and process generators
Args:
gen: Generator or Iterator to validate
Returns:
List of generator values
"""
try:
return list(gen)
except TypeError:
raise ValueError("Invalid generator type")
Validation Method Comparison
Method |
Complexity |
Performance |
Use Case |
isinstance() |
Low |
Fast |
Simple checks |
inspect module |
Medium |
Moderate |
Detailed analysis |
Type Hints |
High |
Slowest |
Static type checking |
Custom Decorator |
Medium |
Moderate |
Runtime validation |
Error Handling Strategies
4. Comprehensive Error Management
def safe_generator_processing(gen):
try:
## Validate generator type
if not validate_generator(gen):
raise TypeError("Invalid generator type")
## Process generator
processed_data = list(gen)
return processed_data
except TypeError as type_error:
print(f"Type Validation Error: {type_error}")
except Exception as e:
print(f"Unexpected error: {e}")
LabEx Python Best Practices
- Use multiple validation techniques
- Combine runtime and static type checking
- Create clear error messages
- Handle edge cases gracefully
- Document type expectations
Type validation adds minimal overhead when implemented efficiently. Choose validation methods based on:
- Performance requirements
- Complexity of type checking
- Specific use case needs