PythonhardPython

Type and Value Validation Decorator

Validate function arguments and return values using type hints and custom validators.

01

The problem

You need to validate function arguments and return values at runtime.

02

The solution

Python
import functools
import inspect
from typing import Any, Callable, Dict, List, get_type_hints

def validate(func: Callable) -> Callable:
    """Validate arguments and return value based on type hints."""
    type_hints = get_type_hints(func)
    signature = inspect.signature(func)
    
    @functools.wraps(func)
    def wrapper(*args, **kwargs) -> Any:
        # Bind arguments to parameters
        bound_args = signature.bind(*args, **kwargs)
        bound_args.apply_defaults()
        
        # Validate arguments
        for param_name, param_value in bound_args.arguments.items():
            if param_name in type_hints:
                expected_type = type_hints[param_name]
                if not isinstance(param_value, expected_type):
                    raise TypeError(
                        f"Argument '{param_name}' must be {expected_type}, "
                        f"got {type(param_value)}"
                    )
        
        # Execute function
        result = func(*args, **kwargs)
        
        # Validate return value
        if 'return' in type_hints:
            expected_return_type = type_hints['return']
            if not isinstance(result, expected_return_type):
                raise TypeError(
                    f"Return value must be {expected_return_type}, "
                    f"got {type(result)}"
                )
        
        return result
    
    return wrapper

03

Put it to work

Example
@validate
def process_data(data: list[int], multiplier: float = 1.0) -> list[float]:
    return [x * multiplier for x in data]

# Valid usage
result = process_data([1, 2, 3], 2.0)  # Returns [2.0, 4.0, 6.0]

# Invalid usage - will raise TypeError
# process_data([1, 2, 3], "2.0")  # TypeError