Advanced Validation
Comprehensive Validation Strategies
Advanced list validation goes beyond simple type and range checks, incorporating sophisticated techniques to ensure data quality and integrity.
Decorator-Based Validation
def validate_list(validator):
def decorator(func):
def wrapper(lst):
if not validator(lst):
raise ValueError("List validation failed")
return func(lst)
return wrapper
return decorator
## Example validator
def strict_numeric_validator(lst):
return all(isinstance(x, (int, float)) for x in lst)
@validate_list(strict_numeric_validator)
def process_numbers(numbers):
return sum(numbers)
## Usage
try:
result = process_numbers([1, 2, 3, 4, 5])
print(result) ## Works fine
process_numbers([1, 2, 'three', 4, 5]) ## Raises ValueError
except ValueError as e:
print(e)
Functional Validation Composition
from functools import reduce
class ListValidator:
@staticmethod
def compose_validators(*validators):
def combined_validator(lst):
return reduce(lambda v1, v2: v1 and v2,
(validator(lst) for validator in validators),
True)
return combined_validator
## Complex validation example
def validate_length(min_len, max_len):
def validator(lst):
return min_len <= len(lst) <= max_len
return validator
def validate_unique(lst):
return len(lst) == len(set(lst))
def validate_numeric_range(min_val, max_val):
def validator(lst):
return all(min_val <= x <= max_val for x in lst)
return validator
## Combining multiple validators
advanced_validator = ListValidator.compose_validators(
validate_length(3, 10),
validate_unique,
validate_numeric_range(0, 100)
)
## Validation demonstration
test_list = [10, 20, 30, 40, 50]
print(advanced_validator(test_list)) ## True
Validation Strategies Comparison
Validation Type |
Complexity |
Performance |
Use Case |
Simple Type Check |
Low |
High |
Basic filtering |
Range Validation |
Medium |
Medium |
Numeric constraints |
Composite Validation |
High |
Low |
Complex data rules |
Decorator-Based |
Medium |
Medium |
Function-level validation |
Machine Learning-Inspired Validation
class SmartValidator:
@staticmethod
def statistical_validation(lst, tolerance=0.1):
import statistics
mean = statistics.mean(lst)
std_dev = statistics.stdev(lst)
def is_within_tolerance(x):
return abs(x - mean) <= (std_dev * tolerance)
return [x for x in lst if is_within_tolerance(x)]
## Usage
data = [10, 15, 20, 25, 100, 200, 300]
cleaned_data = SmartValidator.statistical_validation(data)
print(cleaned_data) ## Removes outliers
Validation Flow Visualization
graph TD
A[Input List] --> B{Type Validation}
B --> |Pass| C{Length Check}
B --> |Fail| D[Type Error]
C --> |Pass| E{Range Validation}
C --> |Fail| F[Length Error]
E --> |Pass| G{Unique Elements}
E --> |Fail| H[Range Error]
G --> |Pass| I[Valid List]
G --> |Fail| J[Duplicate Error]
Advanced Validation Techniques
- Implement context-aware validation
- Use lazy evaluation for performance
- Create flexible, reusable validation frameworks
LabEx Validation Principles
At LabEx, we emphasize creating robust, flexible validation strategies that can adapt to complex data scenarios while maintaining code readability and performance.
Error Handling and Reporting
class ValidationReport:
def __init__(self, errors=None):
self.errors = errors or []
def add_error(self, error):
self.errors.append(error)
def is_valid(self):
return len(self.errors) == 0
def __str__(self):
return "\n".join(self.errors) if self.errors else "No errors"
## Example usage
def validate_complex_list(lst):
report = ValidationReport()
if not lst:
report.add_error("List is empty")
if len(set(lst)) != len(lst):
report.add_error("List contains duplicate elements")
return report
## Demonstration
test_list = [1, 2, 2, 3, 4]
validation_result = validate_complex_list(test_list)
print(validation_result)
print(validation_result.is_valid())