You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Adding type annotation for __pydantic_extra__ only validates values of the extra fields.
I expected that annotating __pydantic_extra__ with something like Dict[constr(pattern="..."), str] would lead to validation of extra field names.
In the example below __pydantic_extra__ is annotated as Dict[constr(pattern="extra"), str] which I expected to lead to validation errors for any extra field names that do not contain "extra".
By default, no validation will be applied to these extra items, but you can set a type for the values by overriding the type annotation for __pydantic_extra__:
should mention that field names are not validated.
Example Code
fromtypingimportDictfromtyping_extensionsimportAnnotatedfrompydanticimportBaseModel, ValidationError, constrclassExtraWithIncorrectValue(BaseModel, extra="allow"):
__pydantic_extra__: Dict[str, int]
# values are validated for extra fieldstry:
ExtraWithIncorrectValue(a="a")
exceptValidationError:
print("ExtraWithIncorrectValue raised an error")
classDictWithIncorrectConstrKey(BaseModel, extra="allow"):
my_dict: Dict[constr(pattern="extra"), str]
# dict keys are validatedtry:
DictWithIncorrectConstrKey(my_dict={"a": "a"})
exceptValidationError:
print("DictWithIncorrectConstrKey raised an error")
classExtraWithIncorrectConstrKey(BaseModel, extra="allow"):
__pydantic_extra__: Dict[constr(pattern="extra"), str]
# extra field names are not validatedExtraWithIncorrectConstrKey(a="a")
print("ExtraWithIncorrectConstrKey did not raise an error")
Marking this as a feature request, because I believe we could add key validation support. I do believe that the current docs make it clear that only validation is applied to the values with the current design.
Initial Checks
Description
Adding type annotation for
__pydantic_extra__
only validates values of the extra fields.I expected that annotating
__pydantic_extra__
with something likeDict[constr(pattern="..."), str]
would lead to validation of extra field names.In the example below
__pydantic_extra__
is annotated asDict[constr(pattern="extra"), str]
which I expected to lead to validation errors for any extra field names that do not contain "extra".If this behavior is intended, documentation
should mention that field names are not validated.
Example Code
Python, Pydantic & OS Version
The text was updated successfully, but these errors were encountered: