Document that omit_defaults ignores custom default_factory - #1076
Merged
Conversation
This was referenced Jun 16, 2026
Comment on lines
+694
to
+695
| still type checks. Specifying ``default=[]`` works too: ``msgspec`` doesn't | ||
| share mutable default values between instances. |
Member
There was a problem hiding this comment.
This isn't true and can be misleading. It is true for builtin mutable collections, but it is not true for any mutable object.
with a list:
>>> import msgspec
>>> DEFAULT = []
>>> class A(msgspec.Struct):
... field: list[int] = msgspec.field(default=DEFAULT)
...
>>> print(A().field is A().field)
Falsewith a custom class:
>>> import msgspec
>>> from collections import UserDict
>>> class MyDict(UserDict):
... pass
...
>>> DEFAULT = MyDict()
>>> class A(msgspec.Struct):
... field: dict[str, int] = msgspec.field(default=DEFAULT)
...
>>> print(A().field is A().field)
True
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
omit_defaultsonly recognizes empty-collection defaults when the default is given by value or via a builtin collection constructor (list/dict/set/tuple/frozenset). A customdefault_factory(a user function,lambda, or aStruct/dataclass/attrstype) is never called during detection, so its field is always encoded, even when the produced value is empty.This is intentional: detection runs in the encode hot path and stays O(1) without invoking user code. The behavior wasn't documented though, so the
matches_defaultsection now spells out thedefault_factorylimitation and points atdefault_factory=list(which type checks fine via the field annotation) as the supported way to omit an empty collection default.Closes #1032
Closes #645