From 670e9c3936cb948c4dc985c6cbeafa4dfb81179f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janek=20Nouvertn=C3=A9?= Date: Sun, 26 Oct 2025 16:36:03 +0100 Subject: [PATCH 1/2] add __replace__ --- msgspec/__init__.pyi | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/msgspec/__init__.pyi b/msgspec/__init__.pyi index 4ad5dec8..dc1878fd 100644 --- a/msgspec/__init__.pyi +++ b/msgspec/__init__.pyi @@ -17,7 +17,7 @@ from typing import ( overload, ) -from typing_extensions import dataclass_transform, Buffer +from typing_extensions import dataclass_transform, Buffer, Self from . import inspect, json, msgpack, structs, toml, yaml @@ -118,6 +118,7 @@ class Struct(metaclass=StructMeta): def __rich_repr__( self, ) -> Iterable[Union[Any, Tuple[Any], Tuple[str, Any], Tuple[str, Any, Any]]]: ... + def __replace__(self, **changes: Any) -> Self: ... def defstruct( name: str, From 477ec738cb96dcb7e073f0b5567fe5277555aca0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janek=20Nouvertn=C3=A9?= Date: Sun, 26 Oct 2025 16:36:16 +0100 Subject: [PATCH 2/2] mention deviations in __post_init__ behaviour --- docs/source/structs.rst | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/source/structs.rst b/docs/source/structs.rst index 334bd994..e83ce822 100644 --- a/docs/source/structs.rst +++ b/docs/source/structs.rst @@ -161,6 +161,14 @@ at the end of the generated ``__init__`` method. It has the same semantics as th This method may be useful for adding additional logic to the init (such as custom validation). +.. important:: + + ``__post_init__`` will *not* be called when using any of + + - :func:`msgspec.structs.replace`, + - :func:`copy.replace`, + - :func:`copy.copy`, + In addition to in ``__init__``, the ``__post_init__`` hook is also called when: - Decoding into a struct type (e.g. ``msgspec.json.decode(..., type=MyStruct)``)