Raise a ValueError
with a helpful message in the else
block,
raise ValueError('x must be in [0, {}]'.format(L))
for example. You could also create a custom DomainError
inheriting from ValueError
class DomainError(ValueError):
pass
and raise that.
In other parts of your code, you just call u
and catch potential exceptions, following the EAFP principle.
edit:
If you need domain-checking for a number of math-like functions, you could also write yourself a simple decorator factory. Here's an example, depending on your use cases you might need to perform some minor modifications.
def domain(lower, upper):
def wrap(f):
def f_new(x):
if not lower <= x <= upper:
raise ValueError('x must be in [{}, {}]'.format(lower, upper))
return f(x)
return f_new
return wrap
Demo:
>>> @domain(0, 10)
...:def f(x):
...: return x + 1
...:
...:
>>> f(2)
>>> 3
>>> f(-1)
[...]
ValueError: x must be in [0, 10]
>>> f(10.1)
[...]
ValueError: x must be in [0, 10]