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
How to use
@validate_types
def add(a: int, b: int) -> int:
return a + b
Top comments (2)
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! ๐ช๐
What are the problems of the code?