Skip to content

prefect.serializers

Serializer implementations for converting objects to bytes and bytes to objects.

All serializers are based on the Serializer class and include a type string that allows them to be referenced without referencing the actual class. For example, you can get often specify the JSONSerializer with the string "json". Some serializers support additional settings for configuration of serialization. These are stored on the instance so the same settings can be used to load saved objects.

All serializers must implement dumps and loads which convert objects to bytes and bytes to an object respectively.

CompressedJSONSerializer

Bases: CompressedSerializer

A compressed serializer preconfigured to use the json serializer.

Source code in prefect/serializers.py
290
291
292
293
294
295
296
class CompressedJSONSerializer(CompressedSerializer):
    """
    A compressed serializer preconfigured to use the json serializer.
    """

    type: Literal["compressed/json"] = "compressed/json"
    serializer: Serializer = pydantic.Field(default_factory=JSONSerializer)

CompressedPickleSerializer

Bases: CompressedSerializer

A compressed serializer preconfigured to use the pickle serializer.

Source code in prefect/serializers.py
281
282
283
284
285
286
287
class CompressedPickleSerializer(CompressedSerializer):
    """
    A compressed serializer preconfigured to use the pickle serializer.
    """

    type: Literal["compressed/pickle"] = "compressed/pickle"
    serializer: Serializer = pydantic.Field(default_factory=PickleSerializer)

CompressedSerializer

Bases: Serializer

Wraps another serializer, compressing its output. Uses lzma by default. See compressionlib for using alternative libraries.

Attributes:

Name Type Description
serializer Serializer

The serializer to use before compression.

compressionlib str

The import path of a compression module to use. Must have methods compress(bytes) -> bytes and decompress(bytes) -> bytes.

level str

If not null, the level of compression to pass to compress.

Source code in prefect/serializers.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
class CompressedSerializer(Serializer):
    """
    Wraps another serializer, compressing its output.
    Uses `lzma` by default. See `compressionlib` for using alternative libraries.

    Attributes:
        serializer: The serializer to use before compression.
        compressionlib: The import path of a compression module to use.
            Must have methods `compress(bytes) -> bytes` and `decompress(bytes) -> bytes`.
        level: If not null, the level of compression to pass to `compress`.
    """

    type: Literal["compressed"] = "compressed"

    serializer: Serializer
    compressionlib: str = "lzma"

    @pydantic.validator("serializer", pre=True)
    def cast_type_names_to_serializers(cls, value):
        if isinstance(value, str):
            return Serializer(type=value)
        return value

    @pydantic.validator("compressionlib")
    def check_compressionlib(cls, value):
        """
        Check that the given pickle library is importable and has compress/decompress
        methods.
        """
        try:
            compresser = from_qualified_name(value)
        except (ImportError, AttributeError) as exc:
            raise ValueError(
                f"Failed to import requested compression library: {value!r}."
            ) from exc

        if not callable(getattr(compresser, "compress", None)):
            raise ValueError(
                f"Compression library at {value!r} does not have a 'compress' method."
            )

        if not callable(getattr(compresser, "decompress", None)):
            raise ValueError(
                f"Compression library at {value!r} does not have a 'decompress' method."
            )

        return value

    def dumps(self, obj: Any) -> bytes:
        blob = self.serializer.dumps(obj)
        compresser = from_qualified_name(self.compressionlib)
        return base64.encodebytes(compresser.compress(blob))

    def loads(self, blob: bytes) -> Any:
        compresser = from_qualified_name(self.compressionlib)
        uncompressed = compresser.decompress(base64.decodebytes(blob))
        return self.serializer.loads(uncompressed)

check_compressionlib

Check that the given pickle library is importable and has compress/decompress methods.

Source code in prefect/serializers.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
@pydantic.validator("compressionlib")
def check_compressionlib(cls, value):
    """
    Check that the given pickle library is importable and has compress/decompress
    methods.
    """
    try:
        compresser = from_qualified_name(value)
    except (ImportError, AttributeError) as exc:
        raise ValueError(
            f"Failed to import requested compression library: {value!r}."
        ) from exc

    if not callable(getattr(compresser, "compress", None)):
        raise ValueError(
            f"Compression library at {value!r} does not have a 'compress' method."
        )

    if not callable(getattr(compresser, "decompress", None)):
        raise ValueError(
            f"Compression library at {value!r} does not have a 'decompress' method."
        )

    return value

JSONSerializer

Bases: Serializer

Serializes data to JSON.

Input types must be compatible with the stdlib json library.

Wraps the json library to serialize to UTF-8 bytes instead of string types.

Source code in prefect/serializers.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
class JSONSerializer(Serializer):
    """
    Serializes data to JSON.

    Input types must be compatible with the stdlib json library.

    Wraps the `json` library to serialize to UTF-8 bytes instead of string types.
    """

    type: Literal["json"] = "json"
    jsonlib: str = "json"
    object_encoder: Optional[str] = pydantic.Field(
        default="prefect.serializers.prefect_json_object_encoder",
        description=(
            "An optional callable to use when serializing objects that are not "
            "supported by the JSON encoder. By default, this is set to a callable that "
            "adds support for all types supported by Pydantic."
        ),
    )
    object_decoder: Optional[str] = pydantic.Field(
        default="prefect.serializers.prefect_json_object_decoder",
        description=(
            "An optional callable to use when deserializing objects. This callable "
            "is passed each dictionary encountered during JSON deserialization. "
            "By default, this is set to a callable that deserializes content created "
            "by our default `object_encoder`."
        ),
    )
    dumps_kwargs: dict = pydantic.Field(default_factory=dict)
    loads_kwargs: dict = pydantic.Field(default_factory=dict)

    @pydantic.validator("dumps_kwargs")
    def dumps_kwargs_cannot_contain_default(cls, value):
        # `default` is set by `object_encoder`. A user provided callable would make this
        # class unserializable anyway.
        if "default" in value:
            raise ValueError(
                "`default` cannot be provided. Use `object_encoder` instead."
            )
        return value

    @pydantic.validator("loads_kwargs")
    def loads_kwargs_cannot_contain_object_hook(cls, value):
        # `object_hook` is set by `object_decoder`. A user provided callable would make
        # this class unserializable anyway.
        if "object_hook" in value:
            raise ValueError(
                "`object_hook` cannot be provided. Use `object_decoder` instead."
            )
        return value

    def dumps(self, data: Any) -> bytes:
        json = from_qualified_name(self.jsonlib)
        kwargs = self.dumps_kwargs.copy()
        if self.object_encoder:
            kwargs["default"] = from_qualified_name(self.object_encoder)
        result = json.dumps(data, **kwargs)
        if isinstance(result, str):
            # The standard library returns str but others may return bytes directly
            result = result.encode()
        return result

    def loads(self, blob: bytes) -> Any:
        json = from_qualified_name(self.jsonlib)
        kwargs = self.loads_kwargs.copy()
        if self.object_decoder:
            kwargs["object_hook"] = from_qualified_name(self.object_decoder)
        return json.loads(blob.decode(), **kwargs)

PickleSerializer

Bases: Serializer

Serializes objects using the pickle protocol.

  • Uses cloudpickle by default. See picklelib for using alternative libraries.
  • Stores the version of the pickle library to check for compatibility during deserialization.
  • Wraps pickles in base64 for safe transmission.
Source code in prefect/serializers.py
 73
 74
 75
 76
 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
class PickleSerializer(Serializer):
    """
    Serializes objects using the pickle protocol.

    - Uses `cloudpickle` by default. See `picklelib` for using alternative libraries.
    - Stores the version of the pickle library to check for compatibility during
        deserialization.
    - Wraps pickles in base64 for safe transmission.
    """

    type: Literal["pickle"] = "pickle"

    picklelib: str = "cloudpickle"
    picklelib_version: str = None

    @pydantic.validator("picklelib")
    def check_picklelib(cls, value):
        """
        Check that the given pickle library is importable and has dumps/loads methods.
        """
        try:
            pickler = from_qualified_name(value)
        except (ImportError, AttributeError) as exc:
            raise ValueError(
                f"Failed to import requested pickle library: {value!r}."
            ) from exc

        if not callable(getattr(pickler, "dumps", None)):
            raise ValueError(
                f"Pickle library at {value!r} does not have a 'dumps' method."
            )

        if not callable(getattr(pickler, "loads", None)):
            raise ValueError(
                f"Pickle library at {value!r} does not have a 'loads' method."
            )

        return value

    @pydantic.root_validator
    def check_picklelib_version(cls, values):
        """
        Infers a default value for `picklelib_version` if null or ensures it matches
        the version retrieved from the `pickelib`.
        """
        picklelib = values.get("picklelib")
        picklelib_version = values.get("picklelib_version")

        if not picklelib:
            raise ValueError("Unable to check version of unrecognized picklelib module")

        pickler = from_qualified_name(picklelib)
        pickler_version = getattr(pickler, "__version__", None)

        if not picklelib_version:
            values["picklelib_version"] = pickler_version
        elif picklelib_version != pickler_version:
            warnings.warn(
                (
                    f"Mismatched {picklelib!r} versions. Found {pickler_version} in the"
                    f" environment but {picklelib_version} was requested. This may"
                    " cause the serializer to fail."
                ),
                RuntimeWarning,
                stacklevel=3,
            )

        return values

    def dumps(self, obj: Any) -> bytes:
        pickler = from_qualified_name(self.picklelib)
        blob = pickler.dumps(obj)
        return base64.encodebytes(blob)

    def loads(self, blob: bytes) -> Any:
        pickler = from_qualified_name(self.picklelib)
        return pickler.loads(base64.decodebytes(blob))

check_picklelib

Check that the given pickle library is importable and has dumps/loads methods.

Source code in prefect/serializers.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
@pydantic.validator("picklelib")
def check_picklelib(cls, value):
    """
    Check that the given pickle library is importable and has dumps/loads methods.
    """
    try:
        pickler = from_qualified_name(value)
    except (ImportError, AttributeError) as exc:
        raise ValueError(
            f"Failed to import requested pickle library: {value!r}."
        ) from exc

    if not callable(getattr(pickler, "dumps", None)):
        raise ValueError(
            f"Pickle library at {value!r} does not have a 'dumps' method."
        )

    if not callable(getattr(pickler, "loads", None)):
        raise ValueError(
            f"Pickle library at {value!r} does not have a 'loads' method."
        )

    return value

check_picklelib_version

Infers a default value for picklelib_version if null or ensures it matches the version retrieved from the pickelib.

Source code in prefect/serializers.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
@pydantic.root_validator
def check_picklelib_version(cls, values):
    """
    Infers a default value for `picklelib_version` if null or ensures it matches
    the version retrieved from the `pickelib`.
    """
    picklelib = values.get("picklelib")
    picklelib_version = values.get("picklelib_version")

    if not picklelib:
        raise ValueError("Unable to check version of unrecognized picklelib module")

    pickler = from_qualified_name(picklelib)
    pickler_version = getattr(pickler, "__version__", None)

    if not picklelib_version:
        values["picklelib_version"] = pickler_version
    elif picklelib_version != pickler_version:
        warnings.warn(
            (
                f"Mismatched {picklelib!r} versions. Found {pickler_version} in the"
                f" environment but {picklelib_version} was requested. This may"
                " cause the serializer to fail."
            ),
            RuntimeWarning,
            stacklevel=3,
        )

    return values

Serializer

Bases: BaseModel, Generic[D], abc.ABC

A serializer that can encode objects of type 'D' into bytes.

Source code in prefect/serializers.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
@add_type_dispatch
class Serializer(BaseModel, Generic[D], abc.ABC):
    """
    A serializer that can encode objects of type 'D' into bytes.
    """

    type: str

    @abc.abstractmethod
    def dumps(self, obj: D) -> bytes:
        """Encode the object into a blob of bytes."""

    @abc.abstractmethod
    def loads(self, blob: bytes) -> D:
        """Decode the blob of bytes into an object."""

    class Config:
        extra = "forbid"

dumps abstractmethod

Encode the object into a blob of bytes.

Source code in prefect/serializers.py
61
62
63
@abc.abstractmethod
def dumps(self, obj: D) -> bytes:
    """Encode the object into a blob of bytes."""

loads abstractmethod

Decode the blob of bytes into an object.

Source code in prefect/serializers.py
65
66
67
@abc.abstractmethod
def loads(self, blob: bytes) -> D:
    """Decode the blob of bytes into an object."""

prefect_json_object_decoder

JSONDecoder.object_hook for decoding objects from JSON when previously encoded with prefect_json_object_encoder

Source code in prefect/serializers.py
41
42
43
44
45
46
47
48
49
50
def prefect_json_object_decoder(result: dict):
    """
    `JSONDecoder.object_hook` for decoding objects from JSON when previously encoded
    with `prefect_json_object_encoder`
    """
    if "__class__" in result:
        return pydantic.parse_obj_as(
            from_qualified_name(result["__class__"]), result["data"]
        )
    return result

prefect_json_object_encoder

JSONEncoder.default for encoding objects into JSON with extended type support.

Raises a TypeError to fallback on other encoders on failure.

Source code in prefect/serializers.py
29
30
31
32
33
34
35
36
37
38
def prefect_json_object_encoder(obj: Any) -> Any:
    """
    `JSONEncoder.default` for encoding objects into JSON with extended type support.

    Raises a `TypeError` to fallback on other encoders on failure.
    """
    return {
        "__class__": to_qualified_name(obj.__class__),
        "data": pydantic_encoder(obj),
    }