Schema
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
- gotcha Do not confuse `schema` (keleshev/schema) with `jsonschema`. This library provides a Pythonic way to define and validate data structures, and can generate JSON schema from its definitions. `jsonschema` is a separate library that strictly implements the JSON Schema specification.
- gotcha Since version 0.6.2, `schema.SchemaError` has specific subclasses like `SchemaWrongKey` and `SchemaMissingKeyError`. While `except SchemaError` will still catch these, code that relies on precise error type checking for key-related issues (e.g., `isinstance(e, SchemaWrongKey)`) may need to be updated if it was written before these subclasses were introduced and expected only the base `SchemaError` class for specific key problems.
- deprecated The `schema` library was tested against older Python versions (e.g., Python 2.6, 2.7, 3.2-3.9). These older Python versions are no longer officially supported by the Python Software Foundation and may have security vulnerabilities or compatibility issues with modern libraries.
- gotcha An issue related to `Optional` fields was reverted in version 0.6.4 ("Revert the optional error commit"). This implies a temporary instability or unexpected behavior regarding `Optional` field validation in an intermediate version prior to 0.6.4. Users upgrading from a version that contained this problematic change might have encountered validation issues.
Install
-
pip install schema
Imports
- Schema
from schema import Schema
- And
from schema import And
- Or
from schema import Or
- Use
from schema import Use
- Optional
from schema import Optional
- Regex
from schema import Regex
- SchemaError
from schema import SchemaError
Quickstart
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}")