Registry / serialization / hologram

hologram

JSON →
library0.0.16pypypi✓ verified 22d ago

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.

pip install hologram
INSTALL
IMPORT
SIG · HOLOGRAM
H
hologram
serializationpythonv0.0.16
Install
2.5s avg
Import
265ms
Disk
21MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.0.16 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.280s · 22.5MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.5s · import 0.250s · 23MB
21MB installed
● package 21MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

JsonSchemaMixin
from hologram import JsonSchemaMixin
from hologram.json_schema_mixin import JsonSchemaMixin
The primary mixin for schema generation is directly available from the top-level 'hologram' package.
FieldSpec
from hologram import FieldSpec
ValidationError
from hologram import ValidationError

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}")
Debug
Known issues
gotchaHologram 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`).
fix
Review the GitHub repository's issues and PRs for current activity and known compatibility problems with newer Python versions or type hints before relying on it for critical projects. Consider contributing or forking if you require active maintenance.
affects: <0.1.0
gotchaFor 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.
fix
Always use `FieldSpec` for `Union`, `Optional` with default values where custom metadata is desired, and any other complex type requiring specific JSON schema attributes. Refer to the official documentation for advanced `FieldSpec` usage.
affects: All
gotchaHologram 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.
fix
If `mashumaro` is desired, consult `hologram`'s GitHub README or source code for examples on how to integrate `mashumaro`'s `DataClassDictMixin` with `JsonSchemaMixin` for your dataclasses.
affects: >=0.0.13
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'jsonschema.compat'
The `hologram` library depends on `jsonschema`, and the `jsonschema.compat` module was removed in `jsonschema` version 4.0, causing import failures when `hologram` attempts to use it.
fix
Downgrade the `jsonschema` package to a version less than 4.0 by running `pip install 'jsonschema<4.0'`.
TypeError: Object of type <YourDataclassName> is not JSON serializable
Python's standard `json.dumps()` function cannot natively serialize custom dataclass objects. This error occurs when a `hologram` dataclass instance is passed directly to `json.dumps()` without first converting it to a standard Python dictionary or string using `hologram`'s provided methods.
fix
Use the `to_dict()` or `to_json()` methods provided by `hologram.JsonSchemaMixin` to serialize the dataclass instance: `my_instance.to_dict()` for a dictionary, or `my_instance.to_json()` for a JSON string.
hologram.ValidationError: '<field_name>' is a required property
This error indicates that the JSON data being parsed into a `hologram` dataclass instance is missing a field that is defined as required in the dataclass's schema. `hologram` enforces schema validation during object parsing.
fix
Ensure that the input JSON string includes all fields marked as required in your `hologram` dataclass definition. Alternatively, if the field is optional, update your dataclass definition to use `typing.Optional` and provide a default value (e.g., `field: Optional[str] = None`).
hologram.ValidationError: '<field_name>' is not of type <expected_type>
This validation error occurs when the value provided for a field in the input JSON data does not match the expected Python type hint defined for that field in the `hologram` dataclass.
fix
Correct the type of the value for the specified field in your input JSON data to match the type annotation in your dataclass (e.g., if `field: int`, ensure the JSON provides an integer). If the JSON's type is correct and the dataclass's type hint is wrong, update the dataclass's type hint accordingly.
Upgrade
Version history
0.0.16latest on PyPI · released Mar 24, 2023
Audit
Dependencies
jsonschemarequiredCore dependency for JSON schema generation and validation.
typing-extensionsrequiredRequired for certain type features on Python versions prior to 3.8.
mashumarooptionalProvides alternative serialization/deserialization capabilities, integrated in v0.13.0.
Agent activity
12 hits · last 30 days
node
10
Perplexity
1
Resources
hologram — pip install hologram · libregistry