-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Open
Labels
bug V2Bug related to Pydantic V2Bug related to Pydantic V2v3Under consideration for V3Under consideration for V3
Description
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 theFinal
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 aFieldInfo
instance, it is the default value and we can simply dotype(assignment)
. Else, if the finalFieldInfo
instance has adefault
, apply the same. If it has adefault_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 asAny
.
crossref #10474 (comment), #2768 (comment), #9904.
Example Code
No response
Python, Pydantic & OS Version
2.10
Metadata
Metadata
Assignees
Labels
bug V2Bug related to Pydantic V2Bug related to Pydantic V2v3Under consideration for V3Under consideration for V3