Python Cerberus – A neat and readable way to validate attributes of a dictionary
Do Not Use If-Else For Validating Data Objects In Python Anymore
In Python, it is common to use if-else statements to validate data objects. However, this can be error-prone and difficult to maintain. Cerberus is a Python library that provides a more elegant and efficient way to validate data objects.
What is Cerberus?
Cerberus is a Python library that provides a schema-based validation framework. This means that you can define a schema for your data object, and Cerberus will validate that the data object conforms to the schema.
Cerberus is a powerful and flexible library. It can validate various data objects, including dictionaries, lists, and sets. Cerberus also supports a variety of validation rules, including type checking, length checking, and value checking.
How to Use Cerberus
To use Cerberus, you must first define a schema for your data object. The schema can be defined in various ways, including YAML, JSON, and Python.
Once you have defined a schema, you can use Cerberus to validate data objects. To do this, you pass the data object to the Cerberus validate()
function.
The validate()
function will return a ValidationError
exception if the data object does not conform to the schema. The ValidationError
exception will contain a list of errors that occurred during validation.
Example
The following code shows an example of how to use Cerberus to validate a dictionary:
import cerberus
schema = {
"name": {
"type": "string",
"required": True,
},
"age": {
"type": "integer",
"required": True,
"min": 18,
},
}
data = {
"name": "John Doe",
"age": 21,
}
validator = cerberus.Validator(schema)
errors = validator.validate(data)
if errors:
for error in errors:
print(error)
else:
print("Data is valid")
In this example, the schema variable defines a schema for a dictionary with two keys: name and age. The name key is required and must be a string. The age key is also required and must be an integer
greater than or equal to 18.
The data
the variable defines a dictionary that conforms to the schema.
The validator
the variable is a Cerberus validator object that is initialized with the schema.
The errors
variable is a list of errors that occurred during validation.
The if errors:
block prints the errors if any occur.
The else:
block prints a message if the data is valid.
Conclusion
Cerberus is a powerful and flexible library that can validate various data objects. Cerberus is an excellent alternative to using if-else statements to validate data objects. Cerberus is easier to use, more efficient, and less error-prone.