Pydantic-collections provides the `BaseCollectionModel` class, which allows for the manipulation and validation of collections of Pydantic models. It supports various Pydantic-compatible types within its collections. The library is actively maintained, with releases often corresponding to updates in the Pydantic ecosystem, and the current version is 0.6.0.
pip install pydantic-collectionsVerified import paths — ran on the pinned version, not inferred.
This example demonstrates defining a Pydantic model (`User`) and then using `BaseCollectionModel` to create a validated collection of `User` objects. It shows instantiation and serialization for Pydantic V2.
Upgrade `pydantic-collections` to `0.5.0+` when migrating to Pydantic V2. Review Pydantic's official migration guide for V1 to V2 changes and update method calls and configurations accordingly.
Ensure that items assigned to or appended to a `BaseCollectionModel` instance are pre-validated instances of the expected Pydantic model. If non-strict behavior is desired, consult the library's documentation on how to configure this (e.g., via Pydantic model config).
Avoid overly restrictive `pydantic` version pinning. If you need to use Pydantic V1 features with a V2-compatible `pydantic-collections` version, import from `pydantic.v1` where necessary (available in Pydantic >=1.10.17).
Install the library using pip: `pip install pydantic-collections`
Ensure that items assigned to or appended to a `BaseCollectionModel` instance are pre-validated instances of the expected Pydantic model. For example, if `UserCollection[User]` is expected, pass `User(...)` objects. To allow non-strict behavior, you would typically need to configure Pydantic's model config (though `pydantic-collections` itself emphasizes strictness by default).
Replace `.dict()` with `.model_dump()` and `.json()` with `.model_dump_json()` for `BaseCollectionModel` instances and any contained Pydantic models when using `pydantic-collections` version 0.5.0 or newer with Pydantic V2.
Either use a concrete collection type (e.g., `list`, `set`) instead of abstract ones, or, if truly necessary, set `model_config = ConfigDict(arbitrary_types_allowed=True)` in your `BaseCollectionModel` definition (from Pydantic v2) or `Config.arbitrary_types_allowed = True` (from Pydantic v1) to allow Pydantic to handle types it can't otherwise validate. Alternatively, consider implementing `__get_pydantic_core_schema__` for complex custom types.