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_index(length):
def f(function):
def _f(x):
error(x >= length)
return function(x)
return _f
return f
def require_nonnull(function):
def f(x):
error(not x)
return function(x)
return f
def error(value):
if value:
raise ValueError
@require_nonnull
@check_index(123)
def function(value):
...
function(x)
def check_range(start, stop):
def check(value):
if not start <= value < stop:
raise ValueError(value)
return True
def wrapper(f):
def wrapped(*args, **kwargs):
values = list(args)
values.extend(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)