Schematics

2.1.1 · active · verified Sun Apr 12

Schematics is a Python library for defining, validating, and transforming data structures. It allows combining types into structures, validating them, and transforming data shapes based on simple descriptions, similar to ORM type systems but without a database layer. The current stable version is 2.1.1. While there isn't a strict, regular release cadence, the library has seen active development and maintenance, offering an intuitive API and comprehensive features for modern Python applications.

Warnings

Install

Imports

Quickstart

This quickstart defines a `WeatherReport` model with city (required string), temperature (required decimal), and a default `taken_at` (datetime). It demonstrates successful model instantiation and validation, along with catching `DataError` exceptions for invalid data types and missing required fields.

import datetime
from schematics.models import Model
from schematics.types import StringType, DecimalType, DateTimeType
from schematics.exceptions import DataError

class WeatherReport(Model):
    city = StringType(required=True)
    temperature = DecimalType(required=True)
    taken_at = DateTimeType(default=datetime.datetime.now)

# Create a valid instance
report_data = {'city': 'NYC', 'temperature': 80.5}
t1 = WeatherReport(report_data)
t1.validate()
print(f"Validated report: {t1.to_primitive()}\n")

# Demonstrate validation failure with invalid type
t_fail_type = WeatherReport({'city': 'LA', 'temperature': 'not-a-number'})
try:
    t_fail_type.validate()
except DataError as e:
    print(f"Validation failed (invalid type): {e.messages}")

# Example with missing required field
t_missing_field = WeatherReport({'temperature': 75.0})
try:
    t_missing_field.validate()
except DataError as e:
    print(f"Validation failed (missing field): {e.messages}")

view raw JSON →