jcrist / msgspec

A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML
https://jcristharif.com/msgspec/
BSD 3-Clause "New" or "Revised" License
2.01k stars 59 forks source link

`omit_defaults` supports specifying `tuple`/`frozenset` default values via `default_factory` #653

Closed jcrist closed 3 months ago

jcrist commented 3 months ago

Previously omit_defaults would only detect tuple/frozenset fields containing default values if the default was specified by value.

class Ex(msgspec.Struct, omit_defaults=True):
    x: tuple = ()                                    # omit_defaults would work properly with this spelling
    y: tuple = msgspec.field(default=())             # or with this spelling
    z: tuple = msgspec.field(default_factory=tuple)  # but not with this spelling

We now also support if these types are specified via default_factory (all 3 cases above now properly work with omit_defaults=True).

Note that since tuple and frozenset values are immutable there's no real reason to prefer default_factory for defaults of these types.

Fixes #652.