Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions docs/structs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,23 @@ detection logic is as follows:
... return True
... return False

This detection never calls a ``default_factory``. A field configured with a
custom ``default_factory`` is only omitted when the factory is one of the
builtin collection constructors (``list``, ``dict``, ``set``, ``tuple``, or
``frozenset``). Any other callable (a user-defined function, a ``lambda``, or a
``Struct``/``dataclass``/``attrs`` type) is treated as opaque, so the field is
always encoded, even when the value it produces is empty. To omit an empty
collection default, configure the builtin constructor directly:

.. code-block:: python

>>> class Basket(msgspec.Struct, omit_defaults=True):
... items: list[int] = msgspec.field(default_factory=list)

The field annotation supplies the element type, so ``default_factory=list``
still type checks. Specifying ``default=[]`` works too: ``msgspec`` doesn't
share mutable default values between instances.
Comment on lines +694 to +695

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
False

with 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



.. _forbid-unknown-fields:

Expand Down
Loading