DEV Community

thitkhotauhp9x
thitkhotauhp9x

Posted on

Create decorator to validate types of a method

def validate_types(func):
    def wrapper(*args, **kwargs):
        annotations = func.__annotations__
        param_types = [annotations[param_name] for param_name in annotations]
        for arg, param_type in zip(args, param_types):
            if not isinstance(arg, param_type):
                raise ValueError(f"Expected type '{param_type.__name__}', got '{type(arg).__name__}' instead")
        for param_name in kwargs:
            param_value = kwargs[param_name]
            param_type = annotations[param_name]
            if not isinstance(param_value, param_type):
                raise ValueError(f"Expected type '{param_type.__name__}', got '{type(param_value).__name__}' instead")
        return func(*args, **kwargs)
    return wrapper
Enter fullscreen mode Exit fullscreen mode

How to use

@validate_types
def add(a: int, b: int) -> int:
    return a + b
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
phylis profile image
Phylis Jepchumba, MSc

Hey thitkhotauhp9x, welcome to the community! 🎉

It's awesome to see you diving into creating a decorator for type validation in methods. Kudos to you for taking the initiative to share your knowledge and contribute to the community! Keep up the great work, and I'm looking forward to seeing more of your contributions! 💪😊

Collapse
 
thitkhotauhp9x profile image
thitkhotauhp9x

What are the problems of the code?