API Docs

Structs

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.

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.

Additional class options can be enabled by passing keywords to the class definition (see example below). These configuration options may also be inspected at runtime through the __struct_config__ attribute.

Configuration:
  • frozen (bool, default False) – Whether instances of this type are pseudo-immutable. If true, attribute assignment is disabled and a corresponding __hash__ is defined.

  • order (bool, default False) – If True, __lt__, __le__`, __gt__, and __ge__ methods will be generated for this type.

  • eq (bool, default True) – If True (the default), an __eq__ method will be generated for this type. Set to False to compare based on instance identity alone.

  • kw_only (bool, default False) – If True, all fields will be treated as keyword-only arguments in the generated __init__ method. Default is False.

  • omit_defaults (bool, default False) – Whether fields should be omitted from encoding if the corresponding value is the default for that field. Enabling this may reduce message size, and often also improve encoding & decoding performance.

  • forbid_unknown_fields (bool, default False) – If True, an error is raised if an unknown field is encountered while decoding structs of this type. If False (the default), no error is raised and the unknown field is skipped.

  • tag (str, int, bool, callable, or None, default None) – Used along with tag_field for configuring tagged union support. If either are non-None, then the struct is considered “tagged”. In this case, an extra field (the tag_field) and value (the tag) are added to the encoded message, which can be used to differentiate message types during decoding.

    Set tag=True to enable the default tagged configuration (tag_field is "type", tag is the class name). Alternatively, you can provide a string (or less commonly int) value directly to be used as the tag (e.g. tag="my-tag-value").``tag`` can also be passed a callable that takes the class qualname and returns a valid tag value (e.g. tag=str.lower). See the docs for more information.

  • tag_field (str or None, default None) – The field name to use for tagged union support. If tag is non-None, then this defaults to "type". See the tag docs above for more information.

  • rename (str, mapping, callable, or None, default None) – Controls renaming the field names used when encoding/decoding the struct. May be one of "lower", "upper", "camel", "pascal", or "kebab" to rename in lowercase, UPPERCASE, camelCase, PascalCase, or kebab-case respectively. May also be a mapping from field names to the renamed names (missing fields are not renamed). Alternatively, may be a callable that takes the field name and returns a new name or None to not rename that field. Default is None for no field renaming.

  • repr_omit_defaults (bool, default False) – Whether fields should be omitted from the generated repr if the corresponding value is the default for that field.

  • array_like (bool, default False) – If True, this struct type will be treated as an array-like type during encoding/decoding, rather than a dict-like type (the default). This may improve performance, at the cost of a more inscrutable message encoding.

  • gc (bool, default True) – Whether garbage collection is enabled for this type. Disabling this may help reduce GC pressure, but will prevent reference cycles composed of only gc=False from being collected. It is the user’s responsibility to ensure that reference cycles don’t occur when setting gc=False.

  • weakref (bool, default False) – Whether instances of this type support weak references. Defaults to False.

  • dict (bool, default False) – Whether instances of this type will include a __dict__. Setting this to True will allow adding additional undeclared attributes to a struct instance, which may be useful for holding private runtime state. Defaults to False.

  • cache_hash (bool, default False) – If enabled, the hash of a frozen struct instance will be computed at most once, and then cached on the instance for further reuse. For expensive hash values this can improve performance at the cost of a small amount of memory usage.

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 a frozen Point object.

>>> class Point(Struct, frozen=True):
...     x: float
...     y: float
...
>>> {Point(1.5, 2.0): 1}  # frozen structs are hashable
{Point(x=1.5, y=2.0): 1}
class msgspec.StructMeta(name, bases, namespace, /, **struct_config)

The metaclass for creating Struct types. See its documentation for the available configuration options when subclassing.

StructMeta can be subclassed, and may be combined with abc.ABCMeta to define abstract base Structs. Other metaclass combinations are not supported; they may work by accident but are not considered part of the public API.

Examples

Here we define a metaclass that modifies the default configuration and use it to create a new Struct base class.

>>> from msgspec import Struct, StructMeta
>>> class KwOnlyStructMeta(StructMeta):
...     def __new__(mcls, name, bases, namespace, **struct_config):
...         struct_config.setdefault("kw_only", True)
...         return super().__new__(mcls, name, bases, namespace, **struct_config)
...
>>> class KwOnlyStruct(Struct, metaclass=KwOnlyStructMeta): ...

Any subclass of KwOnlyStruct will have kw_only set to True by default.

>>> class Example(KwOnlyStruct):
...     a: str =
...     b: int
...
>>> Example(b=123)
Example(a='', b=123)
msgspec.field(*, default=NODEFAULT, default_factory=NODEFAULT, name=None)

Configuration for a Struct field.

Parameters:
  • default (Any, optional) – A default value to use for this field.

  • default_factory (callable, optional) – A zero-argument function called to generate a new default value per-instance, rather than using a constant value as in default.

  • name (str, optional) – The name to use when encoding/decoding this field. If present, this will override any struct-level configuration using the rename option for this field.

msgspec.defstruct(name, fields, *, bases=None, module=None, namespace=None, tag_field=None, tag=None, rename=None, omit_defaults=False, forbid_unknown_fields=False, frozen=False, eq=True, order=False, kw_only=False, repr_omit_defaults=False, array_like=False, gc=True, weakref=False, dict=False, cache_hash=False)

Dynamically define a new Struct class.

Parameters:
  • name (str) – The name of the new Struct class.

  • fields (iterable) – An iterable of fields in the new class. Elements may be either name, tuples of (name, type), (name, type, default), or (name, type, msgspec.field). Fields without a specified type will default to typing.Any.

  • bases (tuple, optional) – A tuple of any Struct base classes to use when defining the new class.

  • module (str, optional) – The module name to use for the new class. If not provided, will be inferred from the caller’s stack frame.

  • namespace (dict, optional) – If provided, will be used as the base namespace for the new class. This may be used to add additional methods to the class definition.

  • **kwargs – Additional Struct configuration options. See the Struct docs for more information.

Examples

>>> from msgspec import defstruct, field
>>> User = defstruct(
...     'User',
...     [
...         ('name', str),
...         ('email', str | None, None),
...         ('groups', set[str], field(default_factory=set)),
...     ],
... )
>>> User('alice')
User(name='alice', email=None, groups=set())

See also

Struct

msgspec.structs.replace(struct, /, **changes)

Create a new struct instance of the same type as struct, replacing fields with values from **changes.

Parameters:
  • struct (Struct) – The original struct instance.

  • **changes – Fields and values that should be replaced in the new struct instance.

Returns:

new_struct (Struct) – A new struct instance of the same type as struct.

Examples

>>> class Point(msgspec.Struct):
...     x: int
...     y: int
>>> obj = Point(x=1, y=2)
>>> msgspec.structs.replace(obj, x=3)
Point(x=3, y=2)
msgspec.structs.asdict(struct, /)

Convert a struct to a dict.

This is a one-to-one conversion of the struct instance, modeled after dataclasses.asdict. Every field is included unchanged using its raw attribute name. Struct-level settings (rename, omit_defaults, array_like,