Convert Figma logo to code with AI

alecthomas logovoluptuous

CONTRIBUTIONS ONLY: Voluptuous, despite the name, is a Python data validation library.

1,831
216
1,831
41

Top Related Projects

A lightweight library for converting complex objects to and from simple Python datatypes.

2,904

Schema validation just got Pythonic

An implementation of the JSON Schema specification for Python

Lightweight, extensible data validation library for Python

Python Data Structures for Humans™.

Python Data Validation for Humans™.

Quick Overview

Voluptuous is a Python data validation library. It allows you to define schemas for validating complex data structures, ensuring that data conforms to specific types, formats, and custom rules. Voluptuous is particularly useful for validating configuration files, API inputs, and other structured data.

Pros

  • Flexible and expressive schema definition
  • Supports custom validation functions
  • Provides clear and informative error messages
  • Lightweight with no external dependencies

Cons

  • Steeper learning curve compared to some other validation libraries
  • Documentation could be more comprehensive
  • Limited built-in validators for complex data types (e.g., dates, URLs)
  • Not actively maintained (last release in 2021)

Code Examples

  1. Basic schema validation:
from voluptuous import Schema, Required, All, Length, Range

schema = Schema({
    Required('name'): All(str, Length(min=1)),
    'age': All(int, Range(min=0, max=120)),
    'email': str
})

valid_data = {'name': 'John Doe', 'age': 30, 'email': 'john@example.com'}
schema(valid_data)  # Validates without raising an exception
  1. Custom validation function:
from voluptuous import Schema, Invalid

def is_even(value):
    if value % 2 != 0:
        raise Invalid('Value must be even')
    return value

schema = Schema(is_even)
schema(4)  # Validates
# schema(3)  # Raises Invalid exception
  1. Nested schemas:
from voluptuous import Schema, Required

address_schema = Schema({
    'street': str,
    'city': str,
    'country': str
})

user_schema = Schema({
    Required('name'): str,
    'age': int,
    'address': address_schema
})

user_data = {
    'name': 'Alice',
    'age': 28,
    'address': {
        'street': '123 Main St',
        'city': 'Anytown',
        'country': 'USA'
    }
}

user_schema(user_data)  # Validates the nested structure

Getting Started

To use Voluptuous, first install it using pip:

pip install voluptuous

Then, in your Python code:

from voluptuous import Schema, Required

# Define your schema
schema = Schema({
    Required('username'): str,
    Required('password'): str,
    'email': str
})

# Use the schema to validate data
try:
    validated_data = schema({
        'username': 'johndoe',
        'password': 'secret123',
        'email': 'john@example.com'
    })
    print("Data is valid:", validated_data)
except Exception as e:
    print("Validation error:", str(e))

This example demonstrates how to define a simple schema and use it to validate a dictionary of user data.

Competitor Comparisons

A lightweight library for converting complex objects to and from simple Python datatypes.

Pros of marshmallow

  • More feature-rich, offering advanced serialization and deserialization capabilities
  • Better integration with web frameworks like Flask and SQLAlchemy
  • Extensive documentation and larger community support

Cons of marshmallow

  • Steeper learning curve due to more complex API
  • Slower performance for simple validation tasks
  • Heavier dependency footprint

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)

voluptuous:

from voluptuous import Schema, Required, All, Range, Email

schema = Schema({
    Required('name'): str,
    'email': Email(),
    'age': All(int, Range(min=18, max=99))
})

Both libraries provide schema validation, but marshmallow offers more built-in features for complex data structures and integrations with web frameworks. voluptuous, on the other hand, is simpler and more lightweight, making it easier to learn and potentially faster for basic validation tasks. The choice between the two depends on the specific requirements of your project and the level of complexity you need in your data validation and serialization processes.

2,904

Schema validation just got Pythonic

Pros of Schema

  • Simpler and more intuitive API, making it easier to learn and use
  • Supports both validation and conversion of data in a single step
  • More flexible type system, allowing for custom types and validators

Cons of Schema

  • Less comprehensive documentation compared to Voluptuous
  • Fewer built-in validators and coercers out of the box
  • May have slightly lower performance for complex validations

Code Comparison

Schema:

from schema import Schema, And, Use, Optional

schema = Schema({
    'name': And(str, len),
    'age': And(Use(int), lambda n: 18 <= n <= 99),
    Optional('email'): str
})

Voluptuous:

from voluptuous import Schema, Required, All, Length, Range

schema = Schema({
    Required('name'): All(str, Length(min=1)),
    Required('age'): All(int, Range(min=18, max=99)),
    'email': str
})

Both libraries offer similar functionality for data validation, but Schema's syntax is generally more concise and readable. Voluptuous provides more explicit control over required fields and validation ranges, while Schema achieves similar results with a more compact representation. The choice between the two often comes down to personal preference and specific project requirements.

An implementation of the JSON Schema specification for Python

Pros of jsonschema

  • Follows the JSON Schema standard, providing better interoperability
  • Supports more complex validation scenarios out-of-the-box
  • Larger community and more frequent updates

Cons of jsonschema

  • Can be more verbose for simple validation tasks
  • Steeper learning curve for beginners
  • Slightly slower performance for basic validations

Code Comparison

jsonschema:

from jsonschema import validate

schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer", "minimum": 0}
    },
    "required": ["name", "age"]
}

validate({"name": "John", "age": 30}, schema)

Voluptuous:

from voluptuous import Schema, Required

schema = Schema({
    Required('name'): str,
    Required('age'): int
})

schema({'name': 'John', 'age': 30})

Both libraries offer powerful data validation capabilities, but jsonschema adheres to a standardized format, while Voluptuous provides a more Pythonic approach. jsonschema is better suited for complex, nested structures and interoperability, while Voluptuous shines in simplicity and readability for straightforward validation tasks.

Lightweight, extensible data validation library for Python

Pros of Cerberus

  • More flexible and customizable validation rules
  • Built-in support for normalization and coercion of data
  • Extensive documentation and examples

Cons of Cerberus

  • Slightly more complex syntax for defining schemas
  • Performance may be slower for large datasets
  • Steeper learning curve for beginners

Code Comparison

Voluptuous schema definition:

schema = Schema({
    'name': str,
    'age': All(int, Range(min=0, max=120)),
    'email': Email()
})

Cerberus schema definition:

schema = {
    'name': {'type': 'string'},
    'age': {'type': 'integer', 'min': 0, 'max': 120},
    'email': {'type': 'string', 'regex': r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'}
}

Both Voluptuous and Cerberus are popular Python libraries for data validation. Voluptuous offers a more concise syntax and is generally easier to get started with, while Cerberus provides more advanced features and customization options. The choice between the two depends on the specific requirements of your project and personal preference.

Python Data Structures for Humans™.

Pros of Schematics

  • More comprehensive data modeling capabilities, including nested schemas and complex types
  • Built-in support for serialization and deserialization
  • Extensive documentation and active community support

Cons of Schematics

  • Steeper learning curve due to more complex API
  • Slower performance compared to Voluptuous, especially for large datasets
  • Heavier dependency footprint

Code Comparison

Voluptuous:

from voluptuous import Schema, Required

schema = Schema({
    Required('name'): str,
    'age': int
})

Schematics:

from schematics.models import Model
from schematics.types import StringType, IntType

class Person(Model):
    name = StringType(required=True)
    age = IntType()

Both libraries provide schema validation, but Schematics offers a more object-oriented approach with its Model class. Voluptuous uses a more straightforward dictionary-based schema definition, which can be easier to grasp for simpler use cases. Schematics' approach allows for more complex data modeling and built-in serialization, while Voluptuous focuses primarily on validation with a simpler API.

Python Data Validation for Humans™.

Pros of validators

  • Simpler API with a focus on individual data type validation
  • Extensive collection of pre-built validators for common use cases
  • Lightweight and easy to integrate into existing projects

Cons of validators

  • Less flexible for complex data structures compared to Voluptuous
  • Limited support for custom error messages and validation schemas
  • Fewer options for data coercion and transformation during validation

Code Comparison

validators:

import validators

validators.email("example@example.com")
validators.url("http://example.com")
validators.uuid("123e4567-e89b-12d3-a456-426655440000")

Voluptuous:

from voluptuous import Schema, Required, All, Length, Email

schema = Schema({
    Required('email'): All(str, Email()),
    'url': All(str, Length(min=1)),
    'uuid': All(str, Length(min=36, max=36))
})

The validators library provides simple, standalone functions for validating individual data types, while Voluptuous offers a more comprehensive schema-based approach for validating complex data structures. Validators is easier to use for quick, single-field validations, but Voluptuous provides more flexibility and control over the validation process, especially for nested data structures and custom validation rules.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

CONTRIBUTIONS ONLY

What does this mean? I do not have time to fix issues myself. The only way fixes or new features will be added is by people submitting PRs.

Current status: Voluptuous is largely feature stable. There hasn't been a need to add new features in a while, but there are some bugs that should be fixed.

Why? I no longer use Voluptuous personally (in fact I no longer regularly write Python code). Rather than leave the project in a limbo of people filing issues and wondering why they're not being worked on, I believe this notice will more clearly set expectations.

Voluptuous is a Python data validation library

image image image Test status Coverage status Gitter chat

Voluptuous, despite the name, is a Python data validation library. It is primarily intended for validating data coming into Python as JSON, YAML, etc.

It has three goals:

  1. Simplicity.
  2. Support for complex data structures.
  3. Provide useful error messages.

Contact

Voluptuous now has a mailing list! Send a mail to voluptuous@librelist.com to subscribe. Instructions will follow.

You can also contact me directly via email or Twitter.

To file a bug, create a new issue on GitHub with a short example of how to replicate the issue.

Documentation

The documentation is provided here.

Contribution to Documentation

Documentation is built using Sphinx. You can install it by

pip install -r requirements.txt

For building sphinx-apidoc from scratch you need to set PYTHONPATH to voluptuous/voluptuous repository.

The documentation is provided here.

Changelog

See CHANGELOG.md.

Why use Voluptuous over another validation library?

Validators are simple callables: No need to subclass anything, just use a function.

Errors are simple exceptions: A validator can just raise Invalid(msg) and expect the user to get useful messages.

Schemas are basic Python data structures: Should your data be a dictionary of integer keys to strings? {int: str} does what you expect. List of integers, floats or strings? [int, float, str].

Designed from the ground up for validating more than just forms: Nested data structures are treated in the same way as any other type. Need a list of dictionaries? [{}]

Consistency: Types in the schema are checked as types. Values are compared as values. Callables are called to validate. Simple.

Show me an example

Twitter's user search API accepts query URLs like:

$ curl 'https://api.twitter.com/1.1/users/search.json?q=python&per_page=20&page=1'

To validate this we might use a schema like:

>>> from voluptuous import Schema
>>> schema = Schema({
...   'q': str,
...   'per_page': int,
...   'page': int,
... })

This schema very succinctly and roughly describes the data required by the API, and will work fine. But it has a few problems. Firstly, it doesn't fully express the constraints of the API. According to the API, per_page should be restricted to at most 20, defaulting to 5, for example. To describe the semantics of the API more accurately, our schema will need to be more thoroughly defined:

>>> from voluptuous import Required, All, Length, Range
>>> schema = Schema({
...   Required('q'): All(str, Length(min=1)),
...   Required('per_page', default=5): All(int, Range(min=1, max=20)),
...   'page': All(int, Range(min=0)),
... })

This schema fully enforces the interface defined in Twitter's documentation, and goes a little further for completeness.

"q" is required:

>>> from voluptuous import MultipleInvalid, Invalid
>>> try:
...   schema({})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "required key not provided @ data['q']"
True

...must be a string:

>>> try:
...   schema({'q': 123})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "expected str for dictionary value @ data['q']"
True

...and must be at least one character in length:

>>> try:
...   schema({'q': ''})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "length of value must be at least 1 for dictionary value @ data['q']"
True
>>> schema({'q': '#topic'}) == {'q': '#topic', 'per_page': 5}
True

"per_page" is a positive integer no greater than 20:

>>> try:
...   schema({'q': '#topic', 'per_page': 900})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "value must be at most 20 for dictionary value @ data['per_page']"
True
>>> try:
...   schema({'q': '#topic', 'per_page': -10})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "value must be at least 1 for dictionary value @ data['per_page']"
True

"page" is an integer >= 0:

>>> try:
...   schema({'q': '#topic', 'per_page': 'one'})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc)
"expected int for dictionary value @ data['per_page']"
>>> schema({'q': '#topic', 'page': 1}) == {'q': '#topic', 'page': 1, 'per_page': 5}
True

Defining schemas

Schemas are nested data structures consisting of dictionaries, lists, scalars and validators. Each node in the input schema is pattern matched against corresponding nodes in the input data.

Literals

Literals in the schema are matched using normal equality checks:

>>> schema = Schema(1)
>>> schema(1)
1
>>> schema = Schema('a string')
>>> schema('a string')
'a string'

Types

Types in the schema are matched by checking if the corresponding value is an instance of the type:

>>> schema = Schema(int)
>>> schema(1)
1
>>> try:
...   schema('one')
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "expected int"
True

URLs

URLs in the schema are matched by using urlparse library.

>>> from voluptuous import Url
>>> schema = Schema(Url())
>>> schema('http://w3.org')
'http://w3.org'
>>> try:
...   schema('one')
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "expected a URL"
True

Lists

Lists in the schema are treated as a set of valid values. Each element in the schema list is compared to each value in the input data:

>>> schema = Schema([1, 'a', 'string'])
>>> schema([1])
[1]
>>> schema([1, 1, 1])
[1, 1, 1]
>>> schema(['a', 1, 'string', 1, 'string'])
['a', 1, 'string', 1, 'string']

However, an empty list ([]) is treated as is. If you want to specify a list that can contain anything, specify it as list:

>>> schema = Schema([])
>>> try:
...   schema([1])
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "not a valid value @ data[1]"
True
>>> schema([])
[]
>>> schema = Schema(list)
>>> schema([])
[]
>>> schema([1, 2])
[1, 2]

Sets and frozensets

Sets and frozensets are treated as a set of valid values. Each element in the schema set is compared to each value in the input data:

>>> schema = Schema({42})
>>> schema({42}) == {42}
True
>>> try:
...   schema({43})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "invalid value in set"
True
>>> schema = Schema({int})
>>> schema({1, 2, 3}) == {1, 2, 3}
True
>>> schema = Schema({int, str})
>>> schema({1, 2, 'abc'}) == {1, 2, 'abc'}
True
>>> schema = Schema(frozenset([int]))
>>> try:
...   schema({3})
...   raise AssertionError('Invalid not raised')
... except Invalid as e:
...   exc = e
>>> str(exc) == 'expected a frozenset'
True

However, an empty set (set()) is treated as is. If you want to specify a set that can contain anything, specify it as set:

>>> schema = Schema(set())
>>> try:
...   schema({1})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "invalid value in set"
True
>>> schema(set()) == set()
True
>>> schema = Schema(set)
>>> schema({1, 2}) == {1, 2}
True

Validation functions

Validators are simple callables that raise an Invalid exception when they encounter invalid data. The criteria for determining validity is entirely up to the implementation; it may check that a value is a valid username with pwd.getpwnam(), it may check that a value is of a specific type, and so on.

The simplest kind of validator is a Python function that raises ValueError when its argument is invalid. Conveniently, many builtin Python functions have this property. Here's an example of a date validator:

>>> from datetime import datetime
>>> def Date(fmt='%Y-%m-%d'):
...   return lambda v: datetime.strptime(v, fmt)
>>> schema = Schema(Date())
>>> schema('2013-03-03')
datetime.datetime(2013, 3, 3, 0, 0)
>>> try:
...   schema('2013-03')
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "not a valid value"
True

In addition to simply determining if a value is valid, validators may mutate the value into a valid form. An example of this is the Coerce(type) function, which returns a function that coerces its argument to the given type:

def Coerce(type, msg=None):
    """Coerce a value to a type.

    If the type constructor throws a ValueError, the value will be marked as
    Invalid.
    """
    def f(v):
        try:
            return type(v)
        except ValueError:
            raise Invalid(msg or ('expected %s' % type.__name__))
    return f

This example also shows a common idiom where an optional human-readable message can be provided. This can vastly improve the usefulness of the resulting error messages.

Dictionaries

Each key-value pair in a schema dictionary is validated against each key-value pair in the corresponding data dictionary:

>>> schema = Schema({1: 'one', 2: 'two'})
>>> schema({1: 'one'})
{1: 'one'}

Extra dictionary keys

By default any additional keys in the data, not in the schema will trigger exceptions:

>>> schema = Schema({2: 3})
>>> try:
...   schema({1: 2, 2: 3})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "extra keys not allowed @ data[1]"
True

This behaviour can be altered on a per-schema basis. To allow additional keys use Schema(..., extra=ALLOW_EXTRA):

>>> from voluptuous import ALLOW_EXTRA
>>> schema = Schema({2: 3}, extra=ALLOW_EXTRA)
>>> schema({1: 2, 2: 3})
{1: 2, 2: 3}

To remove additional keys use Schema(..., extra=REMOVE_EXTRA):

>>> from voluptuous import REMOVE_EXTRA
>>> schema = Schema({2: 3}, extra=REMOVE_EXTRA)
>>> schema({1: 2, 2: 3})
{2: 3}

It can also be overridden per-dictionary by using the catch-all marker token extra as a key:

>>> from voluptuous import Extra
>>> schema = Schema({1: {Extra: object}})
>>> schema({1: {'foo': 'bar'}})
{1: {'foo': 'bar'}}

Required dictionary keys

By default, keys in the schema are not required to be in the data:

>>> schema = Schema({1: 2, 3: 4})
>>> schema({3: 4})
{3: 4}

Similarly to how extra_ keys work, this behaviour can be overridden per-schema:

>>> schema = Schema({1: 2, 3: 4}, required=True)
>>> try:
...   schema({3: 4})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "required key not provided @ data[1]"
True

And per-key, with the marker token Required(key):

>>> schema = Schema({Required(1): 2, 3: 4})
>>> try:
...   schema({3: 4})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "required key not provided @ data[1]"
True
>>> schema({1: 2})
{1: 2}

Optional dictionary keys

If a schema has required=True, keys may be individually marked as optional using the marker token Optional(key):

>>> from voluptuous import Optional
>>> schema = Schema({1: 2, Optional(3): 4}, required=True)
>>> try:
...   schema({})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "required key not provided @ data[1]"
True
>>> schema({1: 2})
{1: 2}
>>> try:
...   schema({1: 2, 4: 5})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "extra keys not allowed @ data[4]"
True
>>> schema({1: 2, 3: 4})
{1: 2, 3: 4}

Recursive / nested schema

You can use voluptuous.Self to define a nested schema:

>>> from voluptuous import Schema, Self
>>> recursive = Schema({"more": Self, "value": int})
>>> recursive({"more": {"value": 42}, "value": 41}) == {'more': {'value': 42}, 'value': 41}
True

Extending an existing Schema

Often it comes handy to have a base Schema that is extended with more requirements. In that case you can use Schema.extend to create a new Schema:

>>> from voluptuous import Schema
>>> person = Schema({'name': str})
>>> person_with_age = person.extend({'age': int})
>>> sorted(list(person_with_age.schema.keys()))
['age', 'name']

The original Schema remains unchanged.

Objects

Each key-value pair in a schema dictionary is validated against each attribute-value pair in the corresponding object:

>>> from voluptuous import Object
>>> class Structure(object):
...     def __init__(self, q=None):
...         self.q = q
...     def __repr__(self):
...         return '<Structure(q={0.q!r})>'.format(self)
...
>>> schema = Schema(Object({'q': 'one'}, cls=Structure))
>>> schema(Structure(q='one'))
<Structure(q='one')>

Allow None values

To allow value to be None as well, use Any:

>>> from voluptuous import Any

>>> schema = Schema(Any(None, int))
>>> schema(None)
>>> schema(5)
5

Error reporting

Validators must throw an Invalid exception if invalid data is passed to them. All other exceptions are treated as errors in the validator and will not be caught.

Each Invalid exception has an associated path attribute representing the path in the data structure to our currently validating value, as well as an error_message attribute that contains the message of the original exception. This is especially useful when you want to catch Invalid exceptions and give some feedback to the user, for instance in the context of an HTTP API.

>>> def validate_email(email):
...     """Validate email."""
...     if not "@" in email:
...         raise Invalid("This email is invalid.")
...     return email
>>> schema = Schema({"email": validate_email})
>>> exc = None
>>> try:
...     schema({"email": "whatever"})
... except MultipleInvalid as e:
...     exc = e
>>> str(exc)
"This email is invalid. for dictionary value @ data['email']"
>>> exc.path
['email']
>>> exc.msg
'This email is invalid.'
>>> exc.error_message
'This email is invalid.'

The path attribute is used during error reporting, but also during matching to determine whether an error should be reported to the user or if the next match should be attempted. This is determined by comparing the depth of the path where the check is, to the depth of the path where the error occurred. If the error is more than one level deeper, it is reported.

The upshot of this is that matching is depth-first and fail-fast.

To illustrate this, here is an example schema:

>>> schema = Schema([[2, 3], 6])

Each value in the top-level list is matched depth-first in-order. Given input data of [[6]], the inner list will match the first element of the schema, but the literal 6 will not match any of the elements of that list. This error will be reported back to the user immediately. No backtracking is attempted:

>>> try:
...   schema([[6]])
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "not a valid value @ data[0][0]"
True

If we pass the data [6], the 6 is not a list type and so will not recurse into the first element of the schema. Matching will continue on to the second element in the schema, and succeed:

>>> schema([6])
[6]

Multi-field validation

Validation rules that involve multiple fields can be implemented as custom validators. It's recommended to use All() to do a two-pass validation - the first pass checking the basic structure of the data, and only after that, the second pass applying your cross-field validator:

def passwords_must_match(passwords):
    if passwords['password'] != passwords['password_again']:
        raise Invalid('passwords must match')
    return passwords

schema = Schema(All(
    # First "pass" for field types
    {'password': str, 'password_again': str},
    # Follow up the first "pass" with your multi-field rules
    passwords_must_match
))

# valid
schema({'password': '123', 'password_again': '123'})

# raises MultipleInvalid: passwords must match
schema({'password': '123', 'password_again': 'and now for something completely different'})

With this structure, your multi-field validator will run with pre-validated data from the first "pass" and so will not have to do its own type checking on its inputs.

The flipside is that if the first "pass" of validation fails, your cross-field validator will not run:

# raises Invalid because password_again is not a string
# passwords_must_match() will not run because first-pass validation already failed
schema({'password': '123', 'password_again': 1337})

Running tests

Voluptuous is using pytest:

$ pip install pytest
$ pytest

To also include a coverage report:

$ pip install pytest pytest-cov coverage>=3.0
$ pytest --cov=voluptuous voluptuous/tests/

Other libraries and inspirations

Voluptuous is heavily inspired by Validino, and to a lesser extent, jsonvalidator and json_schema.

pytest-voluptuous is a pytest plugin that helps in using voluptuous validators in asserts.

I greatly prefer the light-weight style promoted by these libraries to the complexity of libraries like FormEncode.