Skip to content

Dataclasses - Support use of Annotated including field as metainfo #107051

@mementum

Description

@mementum

Dataclasses - Support use of Annotated including field as metainfo

dataclasses are great and I make extensive use of them but there is something which I always find non-matching. Example:

from dataclasses import dataclass, field

@dataclass
class Dummy:
    a: int = field(init=False, default=5)

Having declared a to be of type int the assignment is the result of a callable field which (as an end-user) I am not sure it is returning an int

Given that Annotated can convey metainformation, would it not be really appropriate to use it for dataclasses, as in:

from dataclasses import dataclass, field
from typing import Annotated

@dataclass
class Dummy
    a: Annotated[int, field(init=False)] = 5

This should be clearer for anyone:

  • the type for a is int
  • the information that it must not be part of __init__ is in the metainformation inside Annotated with the use of field.
  • And the default value is assigned to a as expected.

Pitch

It modernizes the use of field, allows assigned a default value which actually matches the defined type, rather than relying on type-checkers having workarounds to cover the case.

It does not remove the old syntax.

Previous discussion

https://discuss.python.org/t/dataclasses-make-use-of-annotated/30028

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-dataclassestype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions