Skip to content

Commit dc343d0

Browse files
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.
1 parent a1ec746 commit dc343d0

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

Doc/library/dataclasses.rst

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,27 @@ Module contents
330330
:attr:`!C.t` will be ``20``, and the class attributes :attr:`!C.x` and
331331
:attr:`!C.y` will not be set.
332332

333+
.. warning::
334+
335+
Do not reuse :class:`Field` objects across multiple fields or classes.
336+
Each call to :func:`!field` returns a new object that gets modified
337+
in place by the :deco:`dataclass` decorator. Reusing the same field
338+
object will cause unexpected behavior::
339+
340+
f = field(kw_only=True)
341+
342+
@dataclass
343+
class A:
344+
x: int = f # Don't do this
345+
y: int = f # f is now modified and broken
346+
347+
Instead, call :func:`!field` separately for each field::
348+
349+
@dataclass
350+
class A:
351+
x: int = field(kw_only=True)
352+
y: int = field(kw_only=True)
353+
333354
.. versionchanged:: next
334355
If *metadata* is ``None``, use an empty :class:`frozendict`, instead
335356
of a :func:`~types.MappingProxyType` of an empty :class:`dict`.

0 commit comments

Comments
 (0)