Skip to content

declearn.utils.add_json_support

Add or modify JSON (de)serialization support for a custom type.

Parameters:

Name Type Description Default
cls Type[Any]

Type for which to add (or modify) JSON (de)serialization support.

required
pack Callable[[Any], Any]

Function used to pack objects of type cls into an arbitrary JSON-serializable object or structure.

required
unpack Callable[[Any], Any]

Function used to unpack objects of type cls from the object or structure ouput by the pack function.

required
name Optional[str]

Keyword to use as a marker for serialized instances of type cls (based on which their deserialization scheme will be retrieved). If None, set to cls.__module__ + '.' + cls.__name__.

None
repl bool

Whether to overwrite any existing specification for type cls or using name name. It is highly recommended not to set this to True unless you know precisely what you are doing.

False
Source code in declearn/utils/_json.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def add_json_support(
    cls: Type[Any],
    pack: Callable[[Any], Any],
    unpack: Callable[[Any], Any],
    name: Optional[str] = None,
    repl: bool = False,
) -> None:
    """Add or modify JSON (de)serialization support for a custom type.

    Parameters
    ----------
    cls: type
        Type for which to add (or modify) JSON (de)serialization support.
    pack: func(cls) -> any
        Function used to pack objects of type `cls` into an arbitrary
        JSON-serializable object or structure.
    unpack: func(any) -> cls
        Function used to unpack objects of type `cls` from the object
        or structure ouput by the `pack` function.
    name: str
        Keyword to use as a marker for serialized instances of type `cls`
        (based on which their deserialization scheme will be retrieved).
        If None, set to `cls.__module__ + '.' + cls.__name__`.
    repl: bool, default=False
        Whether to overwrite any existing specification for type `cls`
        or using name `name`. It is *highly* recommended *not* to set
        this to True unless you know precisely what you are doing.
    """
    if name is None:
        name = f"{cls.__module__}.{cls.__name__}"
    spec = SerializeSpec(cls, name, pack, unpack)
    spec.register(repl)