Hologram Library
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
- gotcha Hologram is in a `0.0.x` versioning stage and has infrequent releases (last release May 2022). This may mean slower adoption of new Python features, types, or addressing breaking changes in dependent libraries (like `jsonschema`).
- gotcha For complex type hints or custom schema modifications (e.g., adding descriptions, examples, titles), understanding and correctly using `hologram.FieldSpec` is crucial. Omitting it for complex types might lead to generic or incorrect schema generation.
- gotcha Hologram introduced optional `mashumaro` integration in v0.0.13, which is not the default serialization/deserialization path. If you intend to use `mashumaro` for its performance or specific features, you'll need to explicitly configure it, which might diverge from the basic `JsonSchemaMixin` usage.
Install
-
pip install hologram
Imports
- JsonSchemaMixin
from hologram import JsonSchemaMixin
- FieldSpec
from hologram import FieldSpec
- ValidationError
from hologram import ValidationError
Quickstart
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}")