Constraining parameters
We can add constraints to parameters such as "greater than", "less than or equal to", ...
For example let's constrain our books to those that are published in 21st century or later:
class Book(Configurable):
year = Integer() >= 2000
Constraints can also be applied to meta characteristics of parameters such as their length. Let's constrain the books' title to a minimum length of 10 characters:
class Book(Configurable):
title = String().len >= 10
Constraints can also be manually added via the constrain
method. Let's constrain the books to those that have a minimum of 5 words in their title:
class Book(Configurable):
title = String().constrain(lambda x: len(x.split()) >= 5)
Note that all constraints apply to the parameter's value after is has been transformed (if any transformations are declared, see #3 (closed)).
If one of the applied constraints is not met then the configuration of the instance will fail and raise a ValueError
. For the built-in constraints (such as >=
, ...) the error message also has a specific format:
ValueError: "parameter.name" This message explains what's wrong (here are any details about the constraint)
Examples
class Book(Configurable):
year = Integer() >= 2000
title = String().len >= 10
title.constrain(lambda x: len(x.split()) >= 5)
The HOCON file
year: 1999
title: "A B C D E"
produces the following error upon configuration:
ValueError: "year" Too small (1999 < 2000)
Similarly:
year: 2000
title: "A B C D E"
ValueError: "title" Too short (9 < 10)
And:
year: 2000
title: "Not enough words"
ValueError: "title"
Here the information about what's going wrong is missing since a custom constrain was used (via lambda function). However there is the possibility to specify an error message if the constraint fails:
class Book(Configurable):
title = String().constrain(
lambda x: len(x.split()) >= 5,
'Not enough words'
)
ValueError: "title" Not enough words
The parameter's specified value can also be reused by using {value}
format specifier:
class Book(Configurable):
title = String().constrain(
lambda x: len(x.split()) >= 5,
'Not enough words ({value})'
)
ValueError: "title" Not enough words ('Not enough words')