Constraints
We can add various constraints to parameters, such as "greater than" or "not equal to", which will be matched against the corresponding specified value. In case a constraint is infringed the framework will raise a ValueError
.
Constraints can be declared by using any of the comparison operators (<, <=, >, >=, !=, ==
).
Constraints are checked for after all transformations have been applied.
Constraining meta characteristics
Constraints can as well refer to meta characteristics such as len
or abs
.
Custom constraints
Finally we can add constraints manually by invoking the constrain
method. This method accepts any callable with the convention that the callable shall return True
if the constraint holds and False
otherwise.
Custom error messages
The error message in the previous example is not really verbose since it only contains the name of the parameter which caused the exception. However we can provide a custom error message when declaring a constraint as an additional argument:
Within the error message we can even refer to the underlying value which will then be displayed in the message:
Last updated