I want to validate if a user initialized the following Test class correctly by using decorators. It's the first time I am using decorators, therefore I am a bit unsure about them. The validation criterion is that all the integers must be lower than 11, but there may be some strings or other arguments, where the if statement could fail. Because of the for loop the "critical" arguments (int) must be passed at first. Otherwise the TypeError exception will return func. That is what I got so far, but I am not happy with it:
def validate_max(func):
"""Decorator to validate a function passed as argument.
Args:
func (function): Function to validate.
"""
def wrapper(*args, **kwargs):
# throw away the first argument, because it will be the instance itself
arguments = [arg for arg in args if args.index(arg) != 0]
for arg in arguments:
# try statement, because you may expect a str as one constructor argument
try:
if arg > 10:
raise ValueError("One or more arguments are higher than 10")
except TypeError:
return func(*args, **kwargs)
return wrapper
class Test:
@validate_max
def __init__(self, x, y, name):
"""Constructor of Test class
Args:
x (int): An integer.
y (int): An integer.
name (str): A string.
"""
self.x = x
self.y = y
self.name = name
if __name__ == "__main__":
t = Test(1, 20, "hi")
If you see something else you would handle differently, please let me now.
arguments? Why do you even need that check, and even if you do, why not justarguments = args[1:]?