Idiom #89 Handle invalid argument
You've detected that the integer value of argument x passed to the current function is invalid. Write the idiomatic way to abort the function execution and signal the problem.
def check_range(start, stop):
def check(value):
if not start <= value < stop:
raise ValueError
return True
def wrapper(f):
def wrapped(*args, **kwargs):
values = *args, *kwargs.values()
if all(map(check, values)):
return f(*args, **kwargs)
return wrapped
return wrapper
@check_range(0, 3.14159)
def function(*args, **kwargs):
...
function(x)
def check_index(length):
def wrapper(function):
def wrapped(arg):
error(arg >= length)
return function(arg)
return wrapped
return wrapper
def require_nonnull(function):
def wrapped(arg):
error(arg is None)
return function(arg)
return wrapped
def error(value):
if value:
raise ValueError
@require_nonnull
@check_index(123)
def function(value):
...
function(x)