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 src/prefect/serializers.py
250
251
252
253
254
255
256
257
class CompressedJSONSerializer(CompressedSerializer):
    """
    A compressed serializer preconfigured to use the json serializer.
    """

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

    serializer: Serializer = Field(default_factory=JSONSerializer)

CompressedPickleSerializer

Bases: CompressedSerializer

A compressed serializer preconfigured to use the pickle serializer.

Source code in src/prefect/serializers.py
240
241
242
243
244
245
246
247
class CompressedPickleSerializer(CompressedSerializer):
    """
    A compressed serializer preconfigured to use the pickle serializer.
    """

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

    serializer: Serializer = 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 src/prefect/serializers.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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"

    @field_validator("serializer", mode="before")
    def validate_serializer(cls, value):
        return cast_type_names_to_serializers(value)

    @field_validator("compressionlib")
    def check_compressionlib(cls, value):
        return validate_compressionlib(value)

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

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

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 src/prefect/serializers.py
145
146
147
148
149
150
151
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
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] = 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 "
        ),
    )
    object_decoder: Optional[str] = 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[str, Any] = Field(default_factory=dict)
    loads_kwargs: Dict[str, Any] = Field(default_factory=dict)

    @field_validator("dumps_kwargs")
    def dumps_kwargs_cannot_contain_default(cls, value):
        return validate_dump_kwargs(value)

    @field_validator("loads_kwargs")
    def loads_kwargs_cannot_contain_object_hook(cls, value):
        return validate_load_kwargs(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 src/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
141
142
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: Optional[str] = None

    @field_validator("picklelib")
    def check_picklelib(cls, value):
        return validate_picklelib(value)

    # @model_validator(mode="before")
    # def check_picklelib_version(cls, values):
    #     return validate_picklelib_version(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))

Serializer

Bases: BaseModel, Generic[D], ABC

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

Source code in src/prefect/serializers.py
 72
 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
@register_base_type
class Serializer(BaseModel, Generic[D], abc.ABC):
    """
    A serializer that can encode objects of type 'D' into bytes.
    """

    def __init__(self, **data: Any) -> None:
        type_string = get_dispatch_key(self) if type(self) != Serializer else "__base__"
        data.setdefault("type", type_string)
        super().__init__(**data)

    def __new__(cls: Type[Self], **kwargs) -> Self:
        if "type" in kwargs:
            try:
                subcls = lookup_type(cls, dispatch_key=kwargs["type"])
            except KeyError as exc:
                raise ValidationError(errors=[exc], model=cls)

            return super().__new__(subcls)
        else:
            return super().__new__(cls)

    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."""

    model_config = ConfigDict(extra="forbid")

    @classmethod
    def __dispatch_key__(cls) -> str:
        type_str = cls.model_fields["type"].default
        return type_str if isinstance(type_str, str) else None

dumps(obj) abstractmethod

Encode the object into a blob of bytes.

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

loads(blob) abstractmethod

Decode the blob of bytes into an object.

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

prefect_json_object_decoder(result)

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

Source code in src/prefect/serializers.py
57
58
59
60
61
62
63
64
65
66
67
68
69
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 TypeAdapter(from_qualified_name(result["__class__"])).validate_python(
            result["data"]
        )
    elif "__exc_type__" in result:
        return from_qualified_name(result["__exc_type__"])(result["message"])
    else:
        return result

prefect_json_object_encoder(obj)

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

Raises a TypeError to fallback on other encoders on failure.

Source code in src/prefect/serializers.py
42
43
44
45
46
47
48
49
50
51
52
53
54
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.
    """
    if isinstance(obj, BaseException):
        return {"__exc_type__": to_qualified_name(obj.__class__), "message": str(obj)}
    else:
        return {
            "__class__": to_qualified_name(obj.__class__),
            "data": custom_pydantic_encoder({}, obj),
        }