Voluptuous

0.16.0 · active · verified Thu Apr 09

Voluptuous is a Python data validation library designed for validating data schemas. It allows defining a desired data structure and then validating input data against that structure, raising detailed exceptions for mismatches. The current version is 0.16.0, and it maintains an active release cadence with regular bug fixes and minor feature additions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a schema with required and optional fields, apply various validators (type coercion, regex matching, range checks, custom lambdas), and handle validation errors. It shows how Voluptuous automatically coerces types and handles default values for missing optional fields.

from voluptuous import Schema, Required, Optional, All, Coerce, In, Match, Invalid
import datetime

# Define a schema for user data
user_schema = Schema({
    Required('id'): All(Coerce(int), lambda n: n > 0, msg='ID must be a positive integer'),
    Required('username', default='guest'): All(str, Match(r'^[a-zA-Z0-9_]+$'), msg='Invalid username'),
    Optional('email'): All(str, Match(r'^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$'), msg='Invalid email format'),
    Optional('age', default=18): All(Coerce(int), In(range(18, 100)), msg='Age must be between 18 and 99'),
    Optional('roles', default=['user']): [str],
    'is_active': Coerce(bool),
    Optional('created_at', default=lambda: datetime.datetime.now()): Coerce(datetime.datetime)
})

# Valid data example
valid_data = {
    'id': '123',
    'username': 'john_doe',
    'email': 'john@example.com',
    'age': 30,
    'is_active': True
}

# Invalid data example
invalid_data = {
    'id': 0,
    'username': 'john doe',
    'age': 'twenty',
    'is_active': 'yes' # Coerce(bool) is lenient, will be True
}

# Validate data
try:
    validated_data = user_schema(valid_data)
    print("\n--- Valid Data Validation ---")
    print("Original data:", valid_data)
    print("Validated data:", validated_data)
    print(f"Created at (default):") # validated_data['created_at']

    print("\n--- Invalid Data Validation ---")
    print("Original data:", invalid_data)
    user_schema(invalid_data) # This will raise an Invalid exception

except Invalid as e:
    print(f"Validation failed: {e}")

view raw JSON →