frompydanticimportBaseModel,ConfigDict,ValidationErrorclassUser(BaseModel):model_config=ConfigDict(extra='forbid')name:strtry:User(name='John Doe',age=20)exceptValidationErrorase:print(e)''' 1 validation error for User age Extra inputs are not permitted [type=extra_forbidden, input_value=20, input_type=int] '''
Whether or not models are faux-immutable, i.e. whether __setattr__ is allowed, and also generates
a __hash__() method for the model. This makes instances of the model potentially hashable if all the
attributes are hashable. Defaults to False.
Note
On V1, this setting was called allow_mutation, and was True by default.
Whether to populate models with the value property of enums, rather than the raw enum.
This may be useful if you want to serialize model.model_dump() later. Defaults to False.
The validation does not happen when the data is changed.
In case you want to revalidate the model when the data is changed, you can use validate_assignment=True:
frompydanticimportBaseModel,ValidationErrorclassUser(BaseModel,validate_assignment=True):name:struser=User(name='John Doe')print(user)#> name='John Doe'try:user.name=123exceptValidationErrorase:print(e)''' 1 validation error for User name Input should be a valid string [type=string_type, input_value=123, input_type=int] '''
Whether arbitrary types are allowed for field types. Defaults to False.
frompydanticimportBaseModel,ConfigDict,ValidationError# This is not a pydantic model, it's an arbitrary classclassPet:def__init__(self,name:str):self.name=nameclassModel(BaseModel):model_config=ConfigDict(arbitrary_types_allowed=True)pet:Petowner:strpet=Pet(name='Hedwig')# A simple check of instance type is used to validate the datamodel=Model(owner='Harry',pet=pet)print(model)#> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'print(model.pet)#> <__main__.Pet object at 0x0123456789ab>print(model.pet.name)#> Hedwigprint(type(model.pet))#> <class '__main__.Pet'>try:# If the value is not an instance of the type, it's invalidModel(owner='Harry',pet='Hedwig')exceptValidationErrorase:print(e)''' 1 validation error for Model pet Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str] '''# Nothing in the instance of the arbitrary type is checked# Here name probably should have been a str, but it's not validatedpet2=Pet(name=42)model2=Model(owner='Harry',pet=pet2)print(model2)#> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'print(model2.pet)#> <__main__.Pet object at 0x0123456789ab>print(model2.pet.name)#> 42print(type(model2.pet))#> <class '__main__.Pet'>
A tuple of types that may occur as values of class attributes without annotations. This is
typically used for custom descriptors (classes that behave like property). If an attribute is set on a
class without an annotation and has a type that is not in this tuple (or otherwise recognized by
pydantic), an error will be raised. Defaults to ().
A dict of custom JSON encoders for specific types. Defaults to None.
Deprecated
This config option is a carryover from v1.
We originally planned to remove it in v2 but didn't have a 1:1 replacement so we are keeping it for now.
It is still deprecated and will likely be removed in the future.
(new in V2) If True, strict validation is applied to all fields on the model.
By default, Pydantic attempts to coerce values to the correct type, when possible.
There are situations in which you may want to disable this behavior, and instead raise an error if a value's type
does not match the field's type annotation.
To configure strict mode for all fields on a model, you can set strict=True on the model.
When and how to revalidate models and dataclasses during validation. Accepts the string
values of 'never', 'always' and 'subclass-instances'. Defaults to 'never'.
'never' will not revalidate models and dataclasses during validation
'always' will revalidate models and dataclasses during validation
'subclass-instances' will revalidate models and dataclasses during validation if the instance is a
subclass of the model or dataclass
By default, model and dataclass instances are not revalidated during validation.
A tuple of strings that prevent model to have field which conflict with them.
Defaults to ('model_', )).
Pydantic prevents collisions between model attributes and BaseModel's own methods by
namespacing them with the prefix model_.
importwarningsfrompydanticimportBaseModelwarnings.filterwarnings('error')# Raise warnings as errorstry:classModel(BaseModel):model_prefixed_field:strexceptUserWarningase:print(e)''' Field "model_prefixed_field" has conflict with protected namespace "model_". You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ()`. '''
You can customize this behavior using the protected_namespaces setting:
importwarningsfrompydanticimportBaseModel,ConfigDictwarnings.filterwarnings('error')# Raise warnings as errorstry:classModel(BaseModel):model_prefixed_field:stralso_protect_field:strmodel_config=ConfigDict(protected_namespaces=('protect_me_','also_protect_'))exceptUserWarningase:print(e)''' Field "also_protect_field" has conflict with protected namespace "also_protect_". You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_',)`. '''
While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision,
an error is raised if there is an actual collision with an existing attribute:
frompydanticimportBaseModeltry:classModel(BaseModel):model_validate:strexceptNameErrorase:print(e)''' Field "model_validate" conflicts with member <bound method BaseModel.model_validate of <class 'pydantic.main.BaseModel'>> of protected namespace "model_". '''
Whether to hide inputs when printing errors. Defaults to False.
Pydantic shows the input value and type when it raises ValidationError during the validation.
frompydanticimportBaseModel,ValidationErrorclassModel(BaseModel):a:strtry:Model(a=123)exceptValidationErrorase:print(e)''' 1 validation error for Model a Input should be a valid string [type=string_type, input_value=123, input_type=int] '''
You can hide the input value and type by setting the hide_input_in_errors config to True.
frompydanticimportBaseModel,ConfigDict,ValidationErrorclassModel(BaseModel):a:strmodel_config=ConfigDict(hide_input_in_errors=True)try:Model(a=123)exceptValidationErrorase:print(e)''' 1 validation error for Model a Input should be a valid string [type=string_type] '''
Whether to defer model validator and serializer construction until the first model validation.
This can be useful to avoid the overhead of building models which are only
used nested within other models, or when you want to manually define type namespace via
Model.model_rebuild(_types_namespace=...). Defaults to False.
A custom core schema generator class to use when generating JSON schemas.
Useful if you want to change the way types are validated across an entire model/schema. Defaults to None.
The GenerateSchema interface is subject to change, currently only the string_schema method is public.
Whether fields with default values should be marked as required in the serialization schema. Defaults to False.
This ensures that the serialization schema will reflect the fact a field with a default will always be present
when serializing the model, even though it is not required for validation.
However, there are scenarios where this may be undesirable — in particular, if you want to share the schema
between validation and serialization, and don't mind fields with defaults being marked as not required during
serialization. See #7209 for more details.
If not None, the specified mode will be used to generate the JSON schema regardless of what mode was passed to
the function call. Defaults to None.
This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the
validation schema.
It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation
and serialization that must both be referenced from the same schema; when this happens, we automatically append
-Input to the definition reference for the validation schema and -Output to the definition reference for the
serialization schema. By specifying a json_schema_mode_override though, this prevents the conflict between
the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes
from being added to the definition references.
frompydanticimportBaseModel,ConfigDict,JsonclassModel(BaseModel):a:Json[int]# requires a string to validate, but will dump an intprint(Model.model_json_schema(mode='serialization'))'''{ 'properties': {'a': {'title': 'A', 'type': 'integer'}}, 'required': ['a'], 'title': 'Model', 'type': 'object',}'''classForceInputModel(Model):# the following ensures that even with mode='serialization', we# will get the schema that would be generated for validation.model_config=ConfigDict(json_schema_mode_override='validation')print(ForceInputModel.model_json_schema(mode='serialization'))'''{ 'properties': { 'a': { 'contentMediaType': 'application/json', 'contentSchema': {'type': 'integer'}, 'title': 'A', 'type': 'string', } }, 'required': ['a'], 'title': 'ForceInputModel', 'type': 'object',}'''
If True, enables automatic coercion of any Number type to str in "lax" (non-strict) mode. Defaults to False.
Pydantic doesn't allow number types (int, float, Decimal) to be coerced as type str by default.
fromdecimalimportDecimalfrompydanticimportBaseModel,ConfigDict,ValidationErrorclassModel(BaseModel):value:strtry:print(Model(value=42))exceptValidationErrorase:print(e)''' 1 validation error for Model value Input should be a valid string [type=string_type, input_value=42, input_type=int] '''classModel(BaseModel):model_config=ConfigDict(coerce_numbers_to_str=True)value:strrepr(Model(value=42).value)#> "42"repr(Model(value=42.13).value)#> "42.13"repr(Model(value=Decimal('42.13')).value)#> "42.13"
defto_pascal(snake:str)->str:"""Convert a snake_case string to PascalCase. Args: snake: The string to convert. Returns: The PascalCase string. """camel=snake.title()returnre.sub('([0-9A-Za-z])_(?=[0-9A-Z])',lambdam:m.group(1),camel)
defto_camel(snake:str)->str:"""Convert a snake_case string to camelCase. Args: snake: The string to convert. Returns: The converted camelCase string. """camel=to_pascal(snake)returnre.sub('(^_*[A-Z])',lambdam:m.group(1).lower(),camel)
Convert a PascalCase or camelCase string to snake_case.
Parameters:
Name
Type
Description
Default
camel
str
The string to convert.
required
Returns:
Type
Description
str
The converted string in snake_case.
Source code in pydantic/alias_generators.py
333435363738394041424344
defto_snake(camel:str)->str:"""Convert a PascalCase or camelCase string to snake_case. Args: camel: The string to convert. Returns: The converted string in snake_case. """snake=re.sub(r'([a-zA-Z])([0-9])',lambdam:f'{m.group(1)}_{m.group(2)}',camel)snake=re.sub(r'([a-z0-9])([A-Z])',lambdam:f'{m.group(1)}_{m.group(2)}',snake)returnsnake.lower()