python / python/cpython

Document dataclass field should not be reused

Open
#145,369 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs pending topic-dataclasses
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Documentation

The current implementation of dataclass modifies a field in place. Thereby, the following code will modify f:

from dataclasses import dataclass, field

f = field(kw_only=True)

@dataclass
class A:
    x: int = f
    y: int = f

print(f) # now f.name is filled
# furthermore, A is broken (or does not behave if we used two different field instance)

It can create issues when we have multiple fields that have the same spec and we reuse the same Field instance to set the same metadata to all of them. A class is created but it's garbage.

IMHO, in the docs, we should warn the user to NOT share any Field instance.

Linked PRs
  • gh-145373
  • gh-145387

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the dataclass and Field documentation and the linked PRs gh-145373 and gh-145387. Add a clear warning not to reuse a Field instance across dataclass fields, and consider the example in the issue complete when the documented guidance addresses the resulting mutation and broken class behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
1/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.