NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI · #600 most downloaded on PyPI
A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML.
Last release 5 days ago
29 Sep 2026
Release timing varies
gaps range from 2 weeks to 11 months
Nearly every release is documented
notes for 39 of 40 stable releases
1 version withdrawn
withdrawn after publishing
6 years old
41 releases · first in 2021
One column per quarter.
BREAKING : Setting gc=False on a struct type that has a weakref slot, whether from weakref=True or from a base class, now raises ValueError . On CPyth
gc=False on a struct type that has a weakref slot,weakref=True or from a base class, now raises ValueError.gc=False type withfrozendict support on Python 3.15+ (#1052, #1105).decimal_format to msgspec.json.Encoder andmsgspec.msgpack.Encoder for custom Decimal encoding (#978).Literal[True] and Literal[False] types (#1004).riscv64 wheels (#987).class Foo[T]) and oftypes.GenericAlias instances in type annotations (#962).NameError when creating a Struct with an unquoted forwardtyping.ClassVar annotations (#1097).AttributeError when converting to a Struct type defined in a__name__ (#1072).ValidationError instead of SystemError when convert receives anint for a float target (#1162).raw rather than the misleading any as the expected type when aRaw value is given for a Raw field in convert, and therefore inyaml.decode and toml.decode (#1169).RawTypedDict, or a Raw field with a default_factory on adataclass or an attrs class (#1176).Meta length boundsExt payloads (#1109).Ext.code (#1135).msgspec.to_builtins, and therefore inyaml.encode, for array_like=True structs (#1177).typenode_collect_literal, Meta.__rich_repr__,ms_decode_bigint, and Encoder.__init__ (#1021, #1022,msgspec.inspect.type_info and msgspec.json.schema crashing on mixed-type Literals such as Literal[1, None] (#1080).null last in the anyOf generated for optional unions in JSONminItems in the JSON schema for array_like=True structs whose fields[] or "" rather than a Python set or bytearray object as thedefault for Struct fields with a set or bytearraydefault_factory (#1183).propertyNames formsgspec.json.encode raising TypeError for a dict keyed by a plainenum.Enum with str values (#1118).encode and decode functions andinspect.signature and the rendered docs,Meta type stub, so type checkers reject mixing gtge or lt with le (#700).msgspec.structs.asdict/astuple andmsgspec.to_builtins (#1025).omit_defaults ignores fields with a customdefault_factory (#1076).msgspec.json.decode docstring to say dec_hook should raiseNotImplementedError for unsupported types, not TypeError (#774).Full Changelog: 0.21.1...0.22.0
gc=False on a struct type that has a weakref slot,
whether from weakref=True or from a base class, now raises ValueError.
On CPython 3.12 and later the weakref slot is stored in a pre-header in
front of the instance, so releasing an instance of a gc=False type with
that slot corrupted memory, in most builds crashing the interpreter
outright. The combination worked on 3.10 and 3.11, and the restriction
applies there as well, so that the same class definition behaves the same
way on every supported version ({pr}1207).__dataclass_fields__, as dataclasses.is_dataclass does. Objects that
expose it only through instance attribute access, such as proxies wrapping
a dataclass instance, are now passed to enc_hook, and encoding them raises
TypeError when no enc_hook is given. An enc_hook can return the wrapped
instance, which is then encoded as a dataclass. Objects with a Python-level
__getattr__, such as pydantic models, now reach enc_hook without that
__getattr__ being called ({pr}1196).frozendict support on Python 3.15+ ({pr}1052, {pr}1105).decimal_format to msgspec.json.Encoder and
msgspec.msgpack.Encoder for custom Decimal encoding ({pr}978).Literal[True] and Literal[False] types ({pr}1004).1152).riscv64 wheels ({pr}987).1083).class Foo[T]) and of
types.GenericAlias instances in type annotations ({pr}962).NameError when creating a Struct with an unquoted forward
reference on Python 3.14 ({issue}1165).typing.ClassVar annotations ({pr}1097).TypeError instead of crashing when a base class of a Struct type is
a C extension type that has not been initialized with PyType_Ready yet
({pr}1199).AttributeError when converting to a Struct type defined in a
namespace without a __name__ ({pr}1072).1133).ValidationError instead of SystemError when convert receives an
out-of-range int for a float target ({pr}1162).raw rather than the misleading any as the expected type when a
non-Raw value is given for a Raw field in convert, and therefore in
yaml.decode and toml.decode ({pr}1169).Raw
field in a TypedDict, or a Raw field with a default_factory on a
dataclass or an attrs class ({pr}1176).Meta length bounds
({pr}1172).Ext payloads ({pr}1109).Ext.code ({pr}1135).DecodeError instead of TypeError when a decoded msgpack map key is
unhashable, such as a map or an Ext ({pr}1209).msgspec.to_builtins, and therefore in
yaml.encode, for array_like=True structs ({pr}1177).typenode_collect_literal, Meta.__rich_repr__,
ms_decode_bigint, and Encoder.__init__ ({pr}1021, {pr}1022,
{pr}1023, {pr}1040).ClassVar annotation is present, on every definition of a
Struct type with annotations ({pr}1194).Struct base, including
typing.Generic, on every definition of a Struct type with such a base on
Python 3.12+. The leaked dict could also keep the base class and the objects
in its namespace alive ({pr}1199).msgspec.inspect.type_info and msgspec.json.schema crashing on mixed-type Literals such as Literal[1, None] ({pr}1080).null last in the anyOf generated for optional unions in JSON
schemas ({pr}1028).minItems in the JSON schema for array_like=True structs whose fields
are all optional ({pr}1124).[] or "" rather than a Python set or bytearray object as the
JSON schema default for Struct fields with a set or bytearray
default_factory ({pr}1183).propertyNames for
annotated dictionary key types ({issue}866).msgspec.json.encode raising TypeError for a dict keyed by a plain
enum.Enum with str values ({pr}1118).1060).1044).1077).encode and decode functions and
methods as positional-only in inspect.signature and the rendered docs,
matching runtime behavior ({pr}1116).inspect.signature
and help() output, the rendered docs and the type stubs, including
msgspec.Raw, msgspec.msgpack.Ext, several msgspec.structs functions
and the encode and decode methods of encoders and decoders ({pr}1197).Meta type stub, so type checkers reject mixing gt
with ge or lt with le ({pr}700).1014, {pr}1043, {pr}1053,
{pr}1055, {pr}1057, {pr}1062, {pr}1063, {pr}1064, {pr}1065,
{pr}1074, {pr}1093, {pr}1114, {pr}1116, {pr}1163, {pr}1173,
{pr}1179).msgspec.structs.asdict/astuple and
msgspec.to_builtins ({pr}1025).omit_defaults ignores fields with a custom
default_factory ({pr}1076).msgspec.json.decode docstring to say dec_hook should raise
NotImplementedError for unsupported types, not TypeError ({issue}774).1045).Fix ValidationError and DecodeError raised in dec_hook being incorrectly wrapped in another ValidationError ( #1013 ).
ValidationError and DecodeError raised in dec_hook being incorrectly wrapped in another ValidationError (#1013).NULL dereference in structmeta_get_module_ns (#1016).ms_passes_big_int_constraints (#1017).ref_template parameter in msgspec.json.schema type stub (#1002).order='deterministic' encoder docstrings (#1011).Fix a segfault on Python 3.13+ that could occur when creating structs that contained a __dict__, instead of only using __slots__ (#960).
__dict__, instead of only using __slots__ (#960).msgspec.UNSET (#975).ref_template arg to msgspec.json.schema (#983).libm linkage to some architectures (#993).uniqueItems annotation to set/frozenset JSON schemas (#984).__post_init__ from msgspec.structs.replace/copy.replace (#1000).Support Python 3.14, including freethreaded mode (#852, #877).
StructMeta metaclass (#890, #927, #928, #940, #945).msgspec.inspect.is_struct and msgspec.inspect.is_struct_type functions for checking whether an object is a msgspec.Struct-like instance or class (#950).arm64 builds (#943).aarch64 builds (#937).re.Pattern objects when using pattern constraints of msgspec.Meta (#899).memoryview support for msgspec.msgpack (#836).typing.TypedDict contains incorrect metadata (#853, #947).setuptools-scm as a build dependency instead of vendoring versioneer (#905).just command runner and Dev Container support (#918).Remove deprecated from_builtins ( #761 ).
tuple and frozenset default values are treated identically whether specified by value or default_factory (#653).match_args in StructConfig object (#684).Raw.copy() (#709).decode signatures for PEP 688 (#740).__replace__ method on Struct types, for use with copy.replace (#747).__post_init__ when converting from an object to a Struct (#752).encode_into is passed a buffer smaller than offset (#753).Raw objects as inputs to convert (#754).encode (#755).from_builtins (#761).Enum type whose .value is a supported type (#757).__parameters__ (#772).eval_type_backport to backport type annotations to Python 3.9 (#773).Support coercing integral floats to ints when strict=False ( #619 ).
strict=False (#619)._ when renaming fields to camel or pascal case (#620).memoryview (#624).Generic base class multiple times (#626).order option to all encoders for enforcing deterministic/sorted ordering when encoding. This can help provide a more consistent or human readable output (#627).Struct type with gc=False (#635).Struct types in msgspec.convert (#636).Support unhashable Annotated metadata in msgspec.inspect.type_info ( #566 ).
Annotated metadata in msgspec.inspect.type_info (#566).slots=True, frozen=True (#569).msgspec.structs.fields (#571).str constraints on dict keys when decoding msgpack (#577).UUID subclasses as inputs to msgspec.convert (#592).__eq__ from generated __ne__ if user defines manual __eq__ method on a Struct type (#593).Struct type in the generated hash (#595).cache_hash struct option (#596).msgspec.structs.force_setattr (#600).dict key constraints in generated JSON schema via the propertyNames field (#604).schema_hook for generating JSON schemas for custom types (#605).type aliases (#606).Resolve an issue leading to periodic segfaults when importing msgspec on CPython 3.12
msgspec on CPython 3.12 (#561)Improve type annotation for Struct.__rich_repr__
Support Enum._missing_ hooks for handling unknown enum values ( #532 ).
Support custom builtin_types in msgspec.to_builtins ( #517 ).
Add a new msgspec.json.Decoder.decode_lines method for decoding newline-delimited JSON into a list of values (#485).
msgspec.json.Decoder.decode_lines method for decoding newline-delimited JSON into a list of values (#485).edgedb.Object instances as dataclass-like objects (#501).float values (#510).float keys (#510).float keys (#510).float_hook to msgspec.json.Decoder to support changing the default for how JSON floats are decoded (#511).Ensure None may be explicitly passed to defstruct for module/namespace/bases (#445).
None may be explicitly passed to defstruct for module/namespace/bases (#445).datetime.datetime values from int/float values (interpreted as seconds since the Unix epoch) when strict=False (#452).list, dict, ...) as inputs to convert (#453).str subclasses as keys in to_builtins and all protocol encode methods (#454).decimal.Decimal values (#455).int/float values (#458).str values (#459).dec_hook with a ValidationError (#460).decimal.Decimal values from numeric values (#463)decimal.Decimal values as numeric values (#465).decimal.Decimal values to float in convert (#466).int64/uint64 (#469).__post_init__ method for Struct types (#470).0/1 into bool types when strict=False (#471).__post_init__/__attrs_post_init__ in a ValidationError when decoding (#472).datetime.timedelta types (#475).msgspec.json.Encoder.encode_lines method for encoding an iterable of values as newline-delimited JSON (#479).Deprecate msgspec.from_builtins in favor of `msgspec.convert`. The new convert function provides a superset of the functionality available in the old…
msgspec.from_builtins in favor of msgspec.convert. The new convert function provides a superset of the functionality available in the old from_builtins function. See the converters docs for more information (#431).from_attributes argument to msgspec.convert for allowing conversion between object types with matching attribute names. One use case for this is converting ORM objects to Struct or dataclasses types (#419).Mapping objects as inputs to msgspec.convert. These may be coerced to dict/Struct/dataclasses/attrs types (#427).strict keyword argument to all decode functions, Decoder classes, as well as msgspec.convert. This defaults to True, setting it to false enables a wider set of coercion rules (e.g. coercing a str input to an int). See "Strict" vs "Lax" Mode for more information (#434).msgspec.convert (#431, #418).typing.Any type in msgspec.convert (#435).Decoder types at runtime (#415).UUID (#429).Fix a reference counting bug introduced in 0.15.0 when decoding naive (no timezone) datetime/time objects in both the msgpack and json decoders (#409)
datetime/time objects in both the msgpack and json decoders (#409).Required/NotRequired in TypedDict when __future__.annotations is enabled (#410).datetime/time objects in both the msgpack and json
decoders ({pr}409).typing.Required/typing.NotRequired in typing.TypedDict when
__future__.annotations is enabled ({pr}410).Add support for Generic Struct types (#386, #393).
Struct types (#386, #393).dataclasses and attrs types (#396).typing.TypedDict and typing.NamedTuple types (#398).datetime objects from JSON (#391).__qualname__ when auto-generating Struct tags rather than __name__ (#399).typing.Literal types containing a literal None (#400).Encoder/Decoder methods threadsafe (#402).write_buffer_size kwarg to Encoder (#402).Remove __del__ trashcan usage for structs with gc=False (#369).
__del__ trashcan usage for structs with gc=False (#369).__setattr__ in Struct types (#376).msgspec.json.Decoder. Trying to decode messages into types that JSON doesn't support will now error at decode time, rather than when the decoder is constructed (#381).Further optimize decoding of JSON arrays into lists #363
dict=True on Python 3.11 #365Support encoding and decoding attrs types (#323).
repr_omit_defaults configuration option for omitting struct default values in the repr (#322).__struct_config__ attribute (#328).msgspec.structs.fields utility function for inspecting the fields configured on a Struct (#330).dict configuration option for adding a __dict__ attribute to a Struct (#331).lt and gt constraints on an integer type (#335).msgspec.field() with no arguments (#343).msgspec.from_builtins (#346).int & bytes in msgspec.from_builtins (#346).msgspec.UNSET and msgspec.UnsetType for tracking unset fields. See the docs for more information (#350).msgspec.UNSET singleton to explicitly indicate no default value on struct types, you should now make use of msgspec.NODEFAULT instead (#350).mypy supports typing.dataclass_transform (#352).typing.Final annotations for indicating that an object field should be treated as immutable (#354).name keyword option to msgspec.field for renaming a single field (#356).rename option have changed. See #356 for more information.Fix a memory leak in the JSON decoder introduced in 0.13.0, caused by a reference counting bug when decoding into Struct types (#312).
Struct types (#312).Add to_builtins function for converting messages composed of any supported type to ones composed of only simple builtin types commonly supported by Py
to_builtins function for converting messages composed of any supported type to ones composed of only simple builtin types commonly supported by Python serialization libraries (#258).from_builtins function for converting and validating messages composed of simple builtin types to ones composed of any type msgspec supports (#266, #302).msgspec.yaml module for encoding/decoding YAML (#267).msgspec.toml module for encoding/decoding TOML (#268).msgspec.structs.replace function for creating a copy of an existing Struct with some changes applied (#262).msgspec.structs.asdict and msgspec.structs.astuple functions for converting a struct instance to a dict or tuple respectively (#300).typing.NewType/typing.Annotated types (#272).Struct.__init__ (#273).default_factory configuration for Struct fields (#274).[], {}, set(), bytearray()), mutable default values in Struct types are no longer deepcopied when used. If a different mutable default value is needed, please configure a default_factory instead (#274).typing.ClassVar annotations of Struct types (#281).decimal.Decimal types (#288).collections.abc.MutableMapping/typing.MutableMapping in decoders (#290).dict key when encoding or decoding JSON (#292).Support encoding set and frozenset subclasses (#249).
Support encoding set and frozenset subclasses (#249).
Support encoding/decoding typing.NewType types (#251).
Allow creating a msgspec.Raw object from a str (#252).
Add new experimental msgspec.inspect module for inspecting type annotations. This is intended to be used for building downstream tooling based on msgspec-compatible types. See the docs for more information (#253).
Add new extra field to msgspec.Meta, for storing arbitrary user-defined metadata (#255).
Improved performance for JSON encoding strings (#256).
Improve performance of constructors for Struct types when using keyword arguments (#237).
Improve performance of constructors for Struct types when using keyword arguments (#237).
Support constraints on dict keys for JSON (#239).
Add support for keyword-only arguments in Struct types, matching the behavior of kw_only for dataclasses (#242).
BREAKING: Change the parameter ordering rules used by Struct types to match the behavior of dataclasses. For most users this change shouldn't break anything. However, if your struct definitions have required fields after optional fields, you'll now get an error on import. This error can be fixed by either:
kw_only=True option).See Field Ordering for more information (#242).
Support encoding/decoding dictionaries with integer keys for JSON (#243).
Ignore attributes with leading underscores ("_") when encoding dataclasses
"_") when encoding dataclasses (#234)Add forbid_unknown_fields configuration option to Struct types
forbid_unknown_fields configuration option to Struct types (#210)enum types by value, rather than name (#211)dataclasses (#218)datetime.date objects (#221)uuid.UUID objects (#222)datetime.datetime values without timezones by default (#224).tz constraint to require aware or naive datetime/time objects when decoding (#224).datetime.time objects (#225)msgspec.json.format utility for efficiently pretty-printing already encoded JSON documents (#226).Support greater than microsecond resolution when parsing JSON timestamps
Support for constraints during validation. For example, this allows ensuring a field is an integer >= 0.
Support integer tag values when using tagged unions (#135).
typing.TypedDict types (#142).typing.NamedTuple types (#161).ValidationError (a subclass of DecodeError) to allow differentiating between errors due to a message not matching the schema from those due to the message being invalid JSON (#155).list/dict (#160).typing.Optional (#162).Further reduce the size of packaged wheels (#130).
weakref support for Struct types through a new weakref configuration option (#131).Rename nogc struct option to gc (a breaking change). To disable GC on a Struct instance you now want to specify gc=False instead of nogc=True (#124).
Struct types when your messages have a common structure, but in cases where no type is provided decoding is now much more performant (#120, #121).order and eq configuration options for Struct types, mirroring the dataclasses options of the same name. Order comparisons for Struct types are very performant, roughly 10x to 70x faster than alternative libraries (#122).Struct decoding for both JSON and MessagePack, on average 20% faster (#119).defstruct method for dynamically defining new Struct types at runtime (#105).Struct.__reduce__ (#117).nogc struct option to gc (a breaking change). To disable GC on a Struct instance you now want to specify gc=False instead of nogc=True (#124).Add a new `msgspec.Raw` type for delayed decoding of message fields / serializing already encoded fields.
msgspec.Raw type for delayed decoding of message fields / serializing already encoded fields.omit_defaults option to Struct types (docs). If enabled, fields containing their respective default value will be omitted from serialized message. This improves both encode and decode performance.rename option to Struct types (docs) for altering the field names used for encoding. A major use of this is supporting camelCase JSON field names, while letting Python code use the more standard snake_case field names.nogc=True structs. GC is now avoided in more cases, and nogc=True structs use 16 fewer bytes per instance. Also added a benchmark for how msgspec can interact with application GC usage.frozenset instancesmsgspec.Raw type for delayed decoding of message fields /
serializing already encoded fields ({pr}92).omit_defaults option to Struct types.
If enabled, fields containing their respective default value will be omitted
from serialized message. This improves both encode and decode performance
({pr}94).rename option to Struct types for
altering the field names used for encoding. A major use of this is supporting
camelCase JSON field names, while letting Python code use the more
standard snake_case field names ({pr}98).nogc=True structs.
GC is now avoided in more cases, and nogc=True structs use 16 fewer bytes
per instance. Also added a benchmark for how msgspec can interact with
application GC usage ({pr}93).91).frozenset instances ({pr}95).Rename the Struct option asarray to array_like (a breaking change)
Union of msgspec.Struct types.enum.Enum by 20-30%msgspec.json.decode/msgspec.msgpack.decode with type=SomeStructType. It's still faster to create a Decoder once and call decoder.decode multiple times, but for struct types the overhead of calling the top-level function is decreased significantly.asarray to array_like (a breaking change)Union of msgspec.Struct types ({pr}83).enum.Enum instances by 20-30%
({pr}84).msgspec.json.decode/msgspec.msgpack.decode
with type=SomeStructType. It's still faster to create a Decoder once
and call decoder.decode multiple times, but for struct types the overhead
of calling the top-level function is decreased significantly ({pr}77,
{pr}88).asarray to array_like ({pr}85).Support Literal string types as dict keys in JSON
Literal string types as dict keys in JSONint | float | None)typing.Literal string types as dict keys in JSON ({pr}78).int | float | None)
({pr}75).80).Optimize decoding of Enum types, ~10x faster
Enum types, ~10x fasterIntEnum types, ~12 fastertyping.Literal typesnogc option for Struct types, disabling the cyclic garbage collector for their instancesEnum types, on average ~10x faster ({pr}69).IntEnum types, on average ~12x faster ({pr}68).typing.Literal types ({pr}71).nogc option for Struct types, disabling the cyclic garbage
collector for their instances ({pr}72).This is a major release with several large changes:
This is a major release with several large changes:
msgspec.msgpack submodulemsgspec.jsonimmutable kwarg in msgspec.Struct to frozen to better match python conventionsEncodingError to EncodeError/DecodingError to DecodeError to better match python conventionspyright support, allowing more errors to be statically caught by their type checkermsgspec.Struct typestyping.Union types (with a few restrictions)msgspec.msgpack submodule ({pr}56).msgspec.json ({pr}56).56).immutable kwarg in msgspec.Struct to frozen to better
match python conventions ({pr}60).EncodingError to EncodeError/DecodingError to
DecodeError to better match python conventions ({pr}61).pyright support, allowing more errors to be statically caught by
their type checker ({pr}60).msgspec.Struct types
({pr}53).typing.Union types (with a few
restrictions) ({pr}54).Faster float encoding and decoding
47).48, {pr}50).Use a freelist for small structs to improve struct allocation time.
44).45).Add Encoder.encode_into api, for encoding into an existing buffer without copying
Encoder.encode_into api, for encoding into an existing buffer without copyingdatetime objectsStruct types as hashableStruct types as MessagePack array objects rather than map objects.Encoder.encode_into api, for encoding into an existing buffer without
copying ({pr}34).31).datetime objects ({pr}36).32, {pr}33).Struct types as hashable ({pr}39).Struct types as MessagePack array objects
rather than map objects ({pr}39).Add default callback to encode/Encoder ({pr}21).
default callback to encode/Encoder ({pr}21).Encoder dealloc ({pr}21).- Initial Release
Nothing published for this version
Your coding agent can read these notes before it upgrades. Set up the MCP server →