Skip to content

Document dataclass field should not be reused #145369

@v01dXYZ

Description

@v01dXYZ

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dirpendingThe issue will be closed if no feedback is providedtopic-dataclasses

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions