From dc343d0b4f3522e91928578743f767f03a9aec68 Mon Sep 17 00:00:00 2001 From: Gouri Jain Date: Sun, 1 Mar 2026 04:19:31 +0530 Subject: [PATCH] gh-145369: Document that dataclass field objects should not be reused Add warning to dataclasses documentation explaining that Field objects returned by field() should not be reused across multiple fields or classes, as they are modified in place by the decorator. --- Doc/library/dataclasses.rst | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Doc/library/dataclasses.rst b/Doc/library/dataclasses.rst index 447f05e67d8418..d8fd61e51dc2ad 100644 --- a/Doc/library/dataclasses.rst +++ b/Doc/library/dataclasses.rst @@ -330,6 +330,27 @@ Module contents :attr:`!C.t` will be ``20``, and the class attributes :attr:`!C.x` and :attr:`!C.y` will not be set. + .. warning:: + + Do not reuse :class:`Field` objects across multiple fields or classes. + Each call to :func:`!field` returns a new object that gets modified + in place by the :deco:`dataclass` decorator. Reusing the same field + object will cause unexpected behavior:: + + f = field(kw_only=True) + + @dataclass + class A: + x: int = f # Don't do this + y: int = f # f is now modified and broken + + Instead, call :func:`!field` separately for each field:: + + @dataclass + class A: + x: int = field(kw_only=True) + y: int = field(kw_only=True) + .. versionchanged:: next If *metadata* is ``None``, use an empty :class:`frozendict`, instead of a :func:`~types.MappingProxyType` of an empty :class:`dict`.