Schema

0.7.8 · active · verified Sun Mar 29

Schema is a Python library for validating data structures, such as those obtained from config files, forms, external services, or command-line parsing, often converted from JSON/YAML to Python data types. It is actively maintained with moderate release frequency, typically addressing bug fixes and minor features, with occasional larger updates.

Warnings

Install

Imports

Quickstart

This quickstart defines a schema for a list of personal information entries, including validation for name length, age range (with type conversion), and an optional gender field with specific allowed values. It then attempts to validate both valid and invalid data, demonstrating how `Schema.validate()` works and how `SchemaError` is raised for invalid input.

from schema import Schema, And, Use, Optional, SchemaError

schema = Schema(
    [
        {
            "name": And(str, len),
            "age": And(Use(int), lambda n: 18 <= n <= 99),
            Optional("gender"): And(str, Use(str.lower), lambda s: s in ("male", "female", "other")),
        }
    ]
)

data = [
    {"name": "Sue", "age": "28", "gender": "Female"},
    {"name": "Sam", "age": "42"},
    {"name": "Sacha", "age": "20", "gender": "Other"},
]

try:
    validated_data = schema.validate(data)
    print("Validation successful!")
    print(validated_data)
except SchemaError as e:
    print(f"Validation failed: {e}")

# Example of invalid data
invalid_data = [
    {"name": "Alice", "age": "15"} # Age too young
]

try:
    schema.validate(invalid_data)
except SchemaError as e:
    print(f"Validation failed for invalid data: {e}")

view raw JSON →