Hologram Library

0.0.16 · active · verified Sat Apr 11

Hologram is a Python library that generates JSON schemas from standard Python dataclasses. It provides a `JsonSchemaMixin` that, when added to a dataclass, enables automatic schema generation and object parsing from JSON data. The current version is 0.0.16, with releases being infrequent.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define dataclasses with `JsonSchemaMixin`, including optional fields, lists, unions with `FieldSpec`, and nested models. It then shows how to generate a JSON schema from the dataclass and parse a Python dictionary into a dataclass instance, leveraging Hologram's validation capabilities.

from dataclasses import dataclass, field
from typing import List, Optional, Union
from hologram import FieldSpec, JsonSchemaMixin

@dataclass
class SubModel(JsonSchemaMixin):
    id: int
    name: str

@dataclass
class MyModel(JsonSchemaMixin):
    id: int
    name: str
    optional_field: Optional[str] = None
    list_of_strings: List[str] = field(default_factory=list)
    union_field: Union[str, int] = FieldSpec(
        title='Union Field',
        description='This is a union field.'
    )
    nested_model: SubModel = field(default_factory=lambda: SubModel(id=1, name="default"))

# Generate JSON schema
schema = MyModel.json_schema()
print("Generated Schema:", schema)

# Parse object from dictionary
data = {'id': 1, 'name': 'test model', 'list_of_strings': ['a', 'b'], 'nested_model': {'id': 2, 'name': 'nested test'}} 
try:
    instance = MyModel.parse_object(data)
    print("Parsed Instance:", instance)
except Exception as e:
    print(f"Error parsing object: {e}")

view raw JSON →