Skip to content

Serialization of objects

Reference

measured.json

codecs_installed() -> Generator[None, None, None]

A context within which the standard library's json module will be aware of how to encode and decode measured objects.

Source code in src/measured/json.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
@contextmanager
def codecs_installed() -> Generator[None, None, None]:
    """A context within which the standard library's `json` module will be aware of
    how to encode and decode `measured` objects."""
    outermost_context = False
    if not isinstance(json._default_encoder, MeasuredJSONEncoder):  # type: ignore
        outermost_context = True

    if outermost_context:
        original_encoder = json._default_encoder  # type: ignore
        original_decoder = json._default_decoder  # type: ignore
        original_object_hook = json.loads.__kwdefaults__["object_hook"]

        encoder = MeasuredJSONEncoder()
        decoder = MeasuredJSONDecoder()

        json._default_encoder = encoder  # type: ignore
        json._default_decoder = decoder  # type: ignore
        json.loads.__kwdefaults__["object_hook"] = decoder.object_hook

        try:
            from pydantic.json import ENCODERS_BY_TYPE as PYDANTIC_ENCODERS_BY_TYPE
        except ImportError:  # pragma: no cover
            PYDANTIC_ENCODERS_BY_TYPE = {}

        PYDANTIC_ENCODERS_BY_TYPE[Dimension] = encoder
        PYDANTIC_ENCODERS_BY_TYPE[Prefix] = encoder
        PYDANTIC_ENCODERS_BY_TYPE[Unit] = encoder
        PYDANTIC_ENCODERS_BY_TYPE[Quantity] = encoder

    try:
        yield
    finally:
        if outermost_context:
            json._default_encoder = original_encoder  # type: ignore
            json._default_decoder = original_decoder  # type: ignore
            json.loads.__kwdefaults__["object_hook"] = original_object_hook

            del PYDANTIC_ENCODERS_BY_TYPE[Dimension]
            del PYDANTIC_ENCODERS_BY_TYPE[Prefix]
            del PYDANTIC_ENCODERS_BY_TYPE[Unit]
            del PYDANTIC_ENCODERS_BY_TYPE[Quantity]

install() -> None

Installs the measured library's JSON encoder and decoder as the default

Source code in src/measured/json.py
 99
100
101
def install() -> None:
    """Installs the `measured` library's JSON encoder and decoder as the default"""
    _installer.__enter__()

uninstall() -> None

Uninstalls the measured library's JSON encoder and decoder from the default

Source code in src/measured/json.py
104
105
106
107
108
def uninstall() -> None:
    """Uninstalls the `measured` library's JSON encoder and decoder from the default"""
    global _installer
    _installer.__exit__(None, None, None)
    _installer = codecs_installed()