Voluptuous
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
- breaking Voluptuous dropped support for Python 3.8 in version 0.15.0, and previously dropped Python 3.7 in 0.14.0. The current version (0.16.0) requires Python 3.9 or higher.
- gotcha There were bugs affecting the interaction between `ALLOW_EXTRA` (or `REMOVE_EXTRA`) and the `Any` validator, where extra fields might not be handled as expected or could lead to errors.
- gotcha A bug existed where `In` and `NotIn` validators could fail when used with unsortable containers (e.g., sets containing mixed types or custom objects without a defined comparison).
- gotcha The `Remove` marker did not correctly remove keys that failed validation in some scenarios, leading to potentially invalid data remaining after validation attempts.
Install
-
pip install voluptuous
Imports
- Schema
from voluptuous import Schema
- Required
from voluptuous import Required
- Optional
from voluptuous import Optional
- All
from voluptuous import All
- Any
from voluptuous import Any
- Coerce
from voluptuous import Coerce
- In
from voluptuous import In
- Match
from voluptuous import Match
- Invalid
from voluptuous import Invalid
Quickstart
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}")