API Docs

Encoder

class msgspec.Encoder(*, enc_hook=None, write_buffer_size=512)

A MessagePack encoder.

Parameters
  • enc_hook (callable, optional) – A callable to call for objects that aren’t supported msgspec types. Takes the unsupported object and should return a supported object, or raise a TypeError.

  • write_buffer_size (int, optional) – The size of the internal static write buffer.

encode(obj)

Serialize an object to bytes.

Parameters

obj (Any) – The object to serialize.

Returns

data – The serialized object.

Return type

bytes

encode_into(obj, buffer, offset=0, /)

Serialize an object into an existing bytearray buffer.

Upon success, the buffer will be truncated to the end of the serialized message. Note that the underlying memory buffer won’t be truncated, allowing for efficiently appending additional bytes later.

Parameters
  • obj (Any) – The object to serialize.

  • buffer (bytearray) – The buffer to serialize into.

  • offset (int, optional) – The offset into the buffer to start writing at. Defaults to 0. Set to -1 to start writing at the end of the buffer.

Returns

Return type

None

Decoder

class msgspec.Decoder(type='Any', *, dec_hook=None, ext_hook=None, tzinfo=None)

A MessagePack decoder.

Parameters
  • type (Type, optional) – A Python type (in type annotation form) to decode the object as. If provided, the message will be type checked and decoded as the specified type. Defaults to Any, in which case the message will be decoded using the default MessagePack types.

  • dec_hook (Callable, optional) – An optional callback for handling decoding custom types. Should have the signature dec_hook(type: Type, obj: Any) -> Any, where type is the expected message type, and obj is the decoded representation composed of only basic MessagePack types. This hook should transform obj into type type, or raise a TypeError if unsupported.

  • ext_hook (Callable, optional) – An optional callback for decoding MessagePack extensions. Should have the signature ext_hook(code: int, data: memoryview) -> Any. If provided, this will be called to deserialize all extension types found in the message. Note that data is a memoryview into the larger message buffer - any references created to the underlying buffer without copying the data out will cause the full message buffer to persist in memory. If not provided, extension types will decode as msgspec.Ext objects.

  • tzinfo (datetime.tzinfo, optional) – The timezone to use when decoding datetime.datetime objects. Defaults to None for “naive” datetimes.

decode(buf)

Deserialize an object from bytes.

Parameters

buf (bytes-like) – The message to decode.

Returns

obj – The deserialized object

Return type

Any

Struct

class msgspec.Struct

A base class for defining efficient serializable objects.

Fields are defined using type annotations. Fields may optionally have default values, which result in keyword parameters to the constructor. Note that mutable default values are deepcopied in the constructor to prevent accidental sharing.

Additional class options can be enabled by passing keywords to the class definition (see example below). The following options exist:

  • immutable: whether instances of the class are immutable. If true, attribute assignment is disabled and a corresponding __hash__ is defined.

  • asarray: whether instances of the class should be serialized as MessagePack arrays, rather than dicts (the default).

Structs automatically define __init__, __eq__, __repr__, and __copy__ methods. Additional methods can be defined on the class as needed. Note that __init__/__new__ cannot be overridden, but other methods can. A tuple of the field names is available on the class via the __struct_fields__ attribute if needed.

Examples

Here we define a new Struct type for describing a dog. It has three fields; two required and one optional.

>>> class Dog(Struct):
...     name: str
...     breed: str
...     is_good_boy: bool = True
...
>>> Dog('snickers', breed='corgi')
Dog(name='snickers', breed='corgi', is_good_boy=True)

Additional struct options can be set as part of the class definition. Here we define a new Struct type for an immutable Point object.

>>> class Point(Struct, immutable=True):
...     x: float
...     y: float
...
>>> {Point(1.5, 2.0): 1}  # immutable structs are hashable
{Point(1.5, 2.0): 1}

Ext

class msgspec.Ext(code, data)

A record representing a MessagePack Extension Type.

Parameters
  • code (int) – The integer type code for this extension. Must be between -128 and 127.

  • data (bytes, bytearray, or memoryview) – The byte buffer for this extension. One of bytes, bytearray, memoryview, or any object that implements the buffer protocol.

code

The extension type code

data

The extension data payload

Functions

msgspec.encode(obj, *, enc_hook=None)

Serialize an object to bytes.

Parameters
  • obj (Any) – The object to serialize.

  • enc_hook (callable, optional) – A callable to call for objects that aren’t supported msgspec types. Takes the unsupported object and should return a supported object, or raise a TypeError.

Returns

data – The serialized object.

Return type

bytes

See also

Encoder.encode

msgspec.decode(buf, *, type='Any', dec_hook=None, ext_hook=None, tzinfo=None)

Deserialize an object from bytes.

Parameters
  • buf (bytes-like) – The message to decode.

  • type (Type, optional) – A Python type (in type annotation form) to decode the object as. If provided, the message will be type checked and decoded as the specified type. Defaults to Any, in which case the message will be decoded using the default MessagePack types.

  • dec_hook (Callable, optional) – An optional callback for handling decoding custom types. Should have the signature dec_hook(type: Type, obj: Any) -> Any, where type is the expected message type, and obj is the decoded representation composed of only basic MessagePack types. This hook should transform obj into type type, or raise a TypeError if unsupported.

  • ext_hook (Callable, optional) – An optional callback for decoding MessagePack extensions. Should have the signature ext_hook(code: int, data: memoryview) -> Any. If provided, this will be called to deserialize all extension types found in the message. Note that data is a memoryview into the larger message buffer - any references created to the underlying buffer without copying the data out will cause the full message buffer to persist in memory. If not provided, extension types will decode as msgspec.Ext objects.

  • tzinfo (datetime.tzinfo, optional) – The timezone to use when decoding datetime.datetime objects. Defaults to None for “naive” datetimes.

Returns

obj – The deserialized object

Return type

Any

See also

Decoder.decode

Exceptions

exception msgspec.MsgspecError

Bases: Exception

Base class for all Msgspec exceptions

exception msgspec.EncodingError

Bases: msgspec.MsgspecError

An error occurred while encoding an object

exception msgspec.DecodingError

Bases: msgspec.MsgspecError

An error occurred while decoding an object