Practical Type Verification
Real-World Type Verification Strategies
def calculate_area(length, width):
"""
Calculate rectangle area with strict type checking
"""
if not all(isinstance(x, (int, float)) for x in (length, width)):
raise TypeError("Length and width must be numeric")
if any(x <= 0 for x in (length, width)):
raise ValueError("Dimensions must be positive")
return length * width
## Usage examples
print(calculate_area(5, 3)) ## Valid input
try:
calculate_area("5", 3) ## Raises TypeError
except TypeError as e:
print(e)
Type Verification Patterns
2. Decorator-Based Type Checking
def validate_numeric_types(*types):
def decorator(func):
def wrapper(*args, **kwargs):
for arg in args:
if not isinstance(arg, types):
raise TypeError(f"Invalid type: {type(arg)}")
return func(*args, **kwargs)
return wrapper
return decorator
@validate_numeric_types(int, float)
def multiply_numbers(a, b):
return a * b
## Demonstrations
print(multiply_numbers(4, 5.0)) ## Works
try:
multiply_numbers(4, "5") ## Raises TypeError
except TypeError as e:
print(e)
Type Verification Workflow
graph TD
A[Input Data] --> B{Type Check}
B -->|Valid| C[Process Data]
B -->|Invalid| D[Raise Exception]
D --> E[Handle Error]
3. Type Verification Techniques
Technique |
Use Case |
Complexity |
isinstance() |
Simple type checking |
Low |
Type Decorators |
Function input validation |
Medium |
Custom Validation |
Complex type constraints |
High |
4. Advanced Type Verification
class NumericValidator:
@staticmethod
def validate(value, allow_zero=False, min_value=None, max_value=None):
"""
Comprehensive numeric validation
"""
if not isinstance(value, (int, float)):
raise TypeError("Value must be numeric")
if not allow_zero and value == 0:
raise ValueError("Zero is not allowed")
if min_value is not None and value < min_value:
raise ValueError(f"Value must be >= {min_value}")
if max_value is not None and value > max_value:
raise ValueError(f"Value must be <= {max_value}")
return value
## Usage examples
try:
NumericValidator.validate(10, min_value=5, max_value=15)
NumericValidator.validate(-3, allow_zero=False)
except (TypeError, ValueError) as e:
print(e)
Practical Considerations
- Always validate input types
- Use appropriate error handling
- Provide clear error messages
- Consider performance implications
def efficient_type_check(value):
"""
Lightweight type verification
"""
return type(value) in (int, float, complex)
## Benchmark-friendly approach
def fast_numeric_processing(data):
return [x for x in data if efficient_type_check(x)]
Best Practices for LabEx Developers
- Implement type hints
- Use type checking strategically
- Balance between strictness and flexibility
- Write clear, self-documenting code
By mastering these practical type verification techniques, you'll write more robust and reliable Python applications with LabEx's professional approach to type management.