8000 Fields marked as `Final` with a default value shouldn't be considered as class variables · Issue #11119 · pydantic/pydantic · GitHub
[go: up one dir, main page]

Skip to content
Fields marked as Final with a default value shouldn't be considered as class variables #11119
@Viicos

Description

@Viicos

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Currently:

from typing import Final

from pydantic import BaseModel

class Model(BaseModel):
    a: Final[int]
    b: Final[int] = 1

Model.model_fields.keys()
#> dict_keys(['a'])
Model.__class_vars__
#> {'b'}

Instead, we should follow the typing specification update from this year, i.e. final fields with a default value are still considered as fields, and not as class variables. I'll also note that the behavior is broken when using Annotated (i.e. using Annotated[Final[int], ...] = 1 is not considered a class variable).

TODO:

  • Add a deprecation/user warning when a final field with a default value is used. The warning should tell the user to explicitly use ClassVar.
  • In V3, change the behavior, and update the mypy plugin as necessary. There's also a TODO in FieldInfo.from_annotated_attribute(): if the Final qualifier is used as is (without an explicit type), we should try our best to infer the type from the default (if any). If the assignment is not a FieldInfo instance, it is the default value and we can simply do type(assignment). Else, if the final FieldInfo instance has a default, apply the same. If it has a default_factory, we should try our best but let's not complicate things to much: if the default factory is a type (e.g. dict, list, that when called results in an "empty" instance), use it as the type. Else, infer the type as Any.

crossref #10474 (comment), #2768 (comment), #9904.

Example Code

No response

Python, Pydantic & OS Version

2.10

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V2Bug related to Pydantic V2v3Under consideration for V3

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0