Domain objects
A field must hold a domain object implemented as a normal Python class.
Pydantic · Pipe
Allows model fields to use ordinary Python classes that Pydantic does not know how to validate. When enabled, Pydantic checks the supplied value's instance type rather than validating the object's internals.
Set arbitrary_types_allowed to True in a model's ConfigDict when a field should accept instances of a regular Python class. Pydantic then performs a simple instance check rather than validating that class's internal attributes.
model_config = ConfigDict(arbitrary_types_allowed=True)| Name | Type | Description |
|---|---|---|
arbitrary_types_allowed | bool | Boolean configuration setting controlling whether arbitrary Python classes may be used as field types. |
A model configured to accept arbitrary class instances as field values.
ConfigDict with arbitrary_types_allowed=True to the model.from pydantic import BaseModel, ConfigDict
class Pet:
def __init__(self, name: str):
self.name = name
class Model(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
pet: Pet
model = Model(pet=Pet("Fluffy"))
assert model.pet.name == "Fluffy"The model accepts a Pet instance without requiring Pet to be a Pydantic model.
A field must hold a domain object implemented as a normal Python class.
A model integrates a class supplied by an external library.
Set model_config = ConfigDict(arbitrary_types_allowed=True) on the model. This permits fields annotated with ordinary Python classes, such as Pet, and validates them by checking their type.
Follow-up: What happens to attributes inside the arbitrary object? They are not recursively validated by Pydantic; only the outer instance check is performed.
The default is False, so arbitrary class types are rejected unless the model enables this configuration option. With it enabled, a value must be an instance of the annotated class.
Follow-up: How would you preserve validation of the object's internal data? Define that data in a Pydantic model or add explicit validation outside this configuration option.
Use ConfigDict(arbitrary_types_allowed=True) in the model configuration. The option is useful when integrating domain objects or third-party classes that Pydantic does not model itself.
Follow-up: Does enabling it make every value valid? No; values still need to be instances of the declared arbitrary type.
BaseModelConfigDictValidationError