Top Related Projects
Python Data Structures for Humans™.
A lightweight library for converting complex objects to and from simple Python datatypes.
Schema validation just got Pythonic
CONTRIBUTIONS ONLY: Voluptuous, despite the name, is a Python data validation library.
An implementation of the JSON Schema specification for Python
Data validation using Python type hints
Quick Overview
Cerberus is a lightweight and extensible data validation library for Python. It allows you to define schemas for validating complex data structures, ensuring that your data adheres to specific rules and constraints. Cerberus is particularly useful for validating user inputs, API payloads, and configuration files.
Pros
- Flexible and customizable schema definitions
- Supports nested data structures and complex validation rules
- Easily extensible with custom validators and coercion functions
- Well-documented with comprehensive examples
Cons
- Learning curve for complex validation scenarios
- Performance may be slower compared to some other validation libraries
- Limited built-in data types and validators (though extensible)
- Not as widely adopted as some other validation libraries
Code Examples
- Basic schema validation:
from cerberus import Validator
schema = {'name': {'type': 'string'}, 'age': {'type': 'integer', 'min': 0}}
v = Validator(schema)
data = {'name': 'John Doe', 'age': 30}
print(v.validate(data)) # True
invalid_data = {'name': 'Jane Doe', 'age': -5}
print(v.validate(invalid_data)) # False
print(v.errors) # {'age': ['min value is 0']}
- Nested schema validation:
schema = {
'user': {
'type': 'dict',
'schema': {
'name': {'type': 'string'},
'email': {'type': 'string', 'regex': r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'}
}
}
}
v = Validator(schema)
data = {'user': {'name': 'John Doe', 'email': 'john@example.com'}}
print(v.validate(data)) # True
- Custom validator:
from cerberus import Validator
def validate_even(field, value, error):
if value % 2 != 0:
error(field, "Must be an even number")
schema = {'number': {'type': 'integer', 'check_with': validate_even}}
v = Validator(schema)
print(v.validate({'number': 4})) # True
print(v.validate({'number': 3})) # False
print(v.errors) # {'number': ['Must be an even number']}
Getting Started
To get started with Cerberus, first install it using pip:
pip install cerberus
Then, import the Validator class and define your schema:
from cerberus import Validator
schema = {'name': {'type': 'string'}, 'age': {'type': 'integer', 'min': 0}}
v = Validator(schema)
data = {'name': 'John Doe', 'age': 30}
if v.validate(data):
print("Data is valid")
else:
print("Validation errors:", v.errors)
This basic example demonstrates how to create a simple schema, instantiate a Validator, and validate data against the schema.
Competitor Comparisons
Python Data Structures for Humans™.
Pros of Schematics
- More extensive type support, including custom types and nested schemas
- Built-in serialization and deserialization capabilities
- Better integration with web frameworks like Django and Flask
Cons of Schematics
- Steeper learning curve due to more complex API
- Less frequent updates and maintenance compared to Cerberus
- Slightly more verbose syntax for defining schemas
Code Comparison
Cerberus schema definition:
schema = {
'name': {'type': 'string', 'required': True},
'age': {'type': 'integer', 'min': 0},
'email': {'type': 'string', 'regex': r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'}
}
Schematics schema definition:
from schematics.models import Model
from schematics.types import StringType, IntType
class Person(Model):
name = StringType(required=True)
age = IntType(min_value=0)
email = StringType(regex=r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
Both libraries offer robust schema validation, but Schematics provides a more object-oriented approach with additional features for complex data structures. Cerberus, on the other hand, offers a simpler, dictionary-based schema definition that may be easier for beginners to grasp and use in smaller projects.
A lightweight library for converting complex objects to and from simple Python datatypes.
Pros of marshmallow
- More feature-rich with built-in serialization and deserialization capabilities
- Extensive ecosystem with plugins and integrations for various frameworks
- Better support for complex nested structures and relationships
Cons of marshmallow
- Steeper learning curve due to more complex API
- Slightly slower performance for simple validation tasks
- Larger codebase and dependencies
Code Comparison
marshmallow:
from marshmallow import Schema, fields
class UserSchema(Schema):
name = fields.Str(required=True)
email = fields.Email()
age = fields.Int(validate=lambda n: 18 <= n <= 99)
Cerberus:
schema = {
'name': {'type': 'string', 'required': True},
'email': {'type': 'string', 'regex': r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'},
'age': {'type': 'integer', 'min': 18, 'max': 99}
}
Both marshmallow and Cerberus are popular Python libraries for data validation, but they have different strengths and use cases. marshmallow offers more advanced features and better integration with complex data structures, while Cerberus provides a simpler API and faster performance for basic validation tasks. The choice between the two depends on the specific requirements of your project and the complexity of your data models.
Schema validation just got Pythonic
Pros of Schema
- More flexible and expressive validation rules
- Supports custom validation functions
- Better performance for large datasets
Cons of Schema
- Less comprehensive documentation
- Smaller community and fewer updates
- Limited built-in validators compared to Cerberus
Code Comparison
Cerberus:
schema = {
'name': {'type': 'string', 'required': True},
'age': {'type': 'integer', 'min': 0, 'max': 120}
}
v = Validator(schema)
v.validate({'name': 'John', 'age': 30})
Schema:
schema = Schema({
'name': And(str, len),
'age': And(int, lambda n: 0 <= n <= 120)
})
schema.validate({'name': 'John', 'age': 30})
Both Cerberus and Schema are Python libraries for data validation, but they have different approaches and features. Cerberus offers a more structured and declarative approach with a wide range of built-in validators, while Schema provides a more flexible and programmatic way to define validation rules. The choice between the two depends on the specific requirements of your project, such as the complexity of validation rules, performance needs, and preference for declarative vs. programmatic approaches.
CONTRIBUTIONS ONLY: Voluptuous, despite the name, is a Python data validation library.
Pros of Voluptuous
- More flexible schema definition with Python functions and classes
- Supports custom validation functions for complex scenarios
- Better performance for large datasets due to its implementation
Cons of Voluptuous
- Steeper learning curve due to its more complex API
- Less comprehensive documentation compared to Cerberus
- Fewer built-in validators and coercion functions
Code Comparison
Cerberus schema definition:
schema = {
'name': {'type': 'string', 'required': True},
'age': {'type': 'integer', 'min': 0, 'max': 120}
}
Voluptuous schema definition:
from voluptuous import Schema, Required, All, Range
schema = Schema({
Required('name'): str,
'age': All(int, Range(min=0, max=120))
})
Both Cerberus and Voluptuous are popular Python libraries for data validation. Cerberus offers a more straightforward, declarative approach to schema definition, making it easier for beginners to use. It also provides more extensive documentation and a wider range of built-in validators.
Voluptuous, on the other hand, offers greater flexibility in schema definition and validation, allowing for more complex scenarios. It performs better with large datasets but has a steeper learning curve due to its more advanced API.
The choice between the two depends on the specific requirements of your project, the complexity of your data structures, and your team's familiarity with each library.
An implementation of the JSON Schema specification for Python
Pros of jsonschema
- Supports JSON Schema standards (draft 3, 4, 6, 7, and 2019-09)
- More extensive validation capabilities for complex JSON structures
- Better integration with JSON-based ecosystems and tools
Cons of jsonschema
- Steeper learning curve due to more complex schema definitions
- Less intuitive for simple data validation tasks
- May require more verbose schema definitions for basic use cases
Code Comparison
Cerberus schema example:
schema = {
'name': {'type': 'string', 'required': True},
'age': {'type': 'integer', 'min': 0}
}
jsonschema schema example:
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["name"]
}
Both libraries offer powerful data validation capabilities, but they cater to different use cases. Cerberus is more Python-centric and user-friendly for simple validations, while jsonschema is better suited for complex JSON structures and adheres to JSON Schema standards. The choice between them depends on the specific requirements of your project and the complexity of the data you need to validate.
Data validation using Python type hints
Pros of Pydantic
- Better performance due to its use of Python type hints
- Seamless integration with FastAPI and other modern Python frameworks
- More extensive data validation and serialization capabilities
Cons of Pydantic
- Steeper learning curve, especially for developers new to type hints
- Less flexibility in custom validation rules compared to Cerberus
Code Comparison
Cerberus:
from cerberus import Validator
schema = {'name': {'type': 'string'}, 'age': {'type': 'integer', 'min': 0}}
v = Validator(schema)
v.validate({'name': 'John', 'age': 30})
Pydantic:
from pydantic import BaseModel, Field
class Person(BaseModel):
name: str
age: int = Field(ge=0)
person = Person(name='John', age=30)
Both Cerberus and Pydantic are popular Python libraries for data validation, but they have different approaches and strengths. Cerberus offers a more flexible, schema-based validation system, while Pydantic leverages Python's type hinting for improved performance and integration with modern frameworks. The choice between them often depends on the specific project requirements and the developer's familiarity with type hints.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Cerberus |latest-version|
|python-support| |black|
Cerberus is a lightweight and extensible data validation library for Python.
.. code-block:: python
>>> v = Validator({'name': {'type': 'string'}})
>>> v.validate({'name': 'john doe'})
True
Features
Cerberus provides type checking and other base functionality out of the box and is designed to be non-blocking and easily and widely extensible, allowing for custom validation. It has no dependencies, but has the potential to become yours.
Versioning & Interpreter support
Starting with Cerberus 1.2, it is maintained according to
semantic versioning
_. So, a major release sheds off the old and defines a
space for the new, minor releases ship further new features and improvements
(you know the drill, new bugs are inevitable too), and micro releases polish a
definite amount of features to glory.
We intend to test Cerberus against all CPython interpreters at least until half
a year after their end of life
_ and against the most recent PyPy interpreter
as a requirement for a release. If you still need to use it with a potential
security hole in your setup, it should most probably work with the latest
minor version branch from the time when the interpreter was still tested.
Subsequent minor versions have good chances as well. In any case, you are
advised to run the contributed test suite on your target system.
Documentation
Complete documentation is available at http://docs.python-cerberus.org
Installation
Cerberus is on PyPI_, so all you need to do is:
.. code-block:: console
$ pip install cerberus
Testing
Just run:
.. code-block:: console
$ python setup.py test
Or you can use tox to run the tests under all supported Python versions. Make sure the required python versions are installed and run:
.. code-block:: console
$ pip install tox # first time only
$ tox
Contributing
Please see the Contribution Guidelines
_.
Copyright
Cerberus is an open source project by Nicola Iarocci
. See the license file
for more information.
.. _Contribution Guidelines: https://github.com/pyeve/cerberus/blob/1.3.x/CONTRIBUTING.rst .. _end of life: https://devguide.python.org/#status-of-python-branches .. _license: https://github.com/pyeve/cerberus/blob/1.3.x/LICENSE .. _Nicola Iarocci: https://nicolaiarocci.com/ .. _PyPI: https://pypi.python.org/ .. _semantic versioning: https://semver.org/
.. |black| image:: https://img.shields.io/badge/code%20style-black-000000.svg :alt: Black code style :target: https://black.readthedocs.io/ .. |latest-version| image:: https://img.shields.io/pypi/v/cerberus.svg :alt: Latest version on PyPI :target: https://pypi.org/project/cerberus .. |license| image:: https://img.shields.io/pypi/l/cerberus.svg :alt: Software license :target: https://github.com/pyeve/cerberus/blob/1.3.x/LICENSE .. |python-support| image:: https://img.shields.io/pypi/pyversions/cerberus.svg :target: https://pypi.python.org/pypi/cerberus :alt: Python versions
Top Related Projects
Python Data Structures for Humans™.
A lightweight library for converting complex objects to and from simple Python datatypes.
Schema validation just got Pythonic
CONTRIBUTIONS ONLY: Voluptuous, despite the name, is a Python data validation library.
An implementation of the JSON Schema specification for Python
Data validation using Python type hints
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot