pydantic
gitversioned.utils.pydantic ¶
Pydantic helpers for GitVersioned.
This module provides reusable validation and type-coercion helpers for Pydantic models, integrating directly with the Pydantic core schema for performance. These helpers ensure robust parsing of configurations and environment variables, supporting list parsing from strings and boolean evaluation of truthy/falsy strings.
EnsureList ¶
Bases: list[TypeVarT], Generic[TypeVarT]
A list subclass that tightly integrates with Pydantic Core Schema.
It preprocesses inputs (splitting strings, normalizing bools) before delegating the final strict validation to Pydantic's native schema.
.. code-block:: python
from pydantic import BaseModel
class MyModel(BaseModel):
items: EnsureList[int]
model = MyModel(items="1, 2, 3")
print(model.items) # [1, 2, 3]
Source code in src/gitversioned/utils/pydantic.py
__get_pydantic_core_schema__(source_type, handler) classmethod ¶
Create a schema that hooks a pre-validator into the Pydantic pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_type | Any | The original type annotation. | required |
handler | GetCoreSchemaHandler | The Pydantic core schema handler. | required |
Returns:
| Type | Description |
|---|---|
CoreSchema | The constructed Pydantic core schema. |
Source code in src/gitversioned/utils/pydantic.py
coerce_bool(value) ¶
Normalize truthy/falsy strings to actual booleans.
.. code-block:: python
coerce_bool("yes") # True
coerce_bool("0") # False
coerce_bool(5) # 5
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | Any | The value to coerce. | required |
Returns:
| Type | Description |
|---|---|
bool | Any | The boolean equivalent if recognizable, otherwise the original value. |
Source code in src/gitversioned/utils/pydantic.py
coerce_list(value, item_pre_coercer=None) ¶
Recursively transform input into a list.
Splits strings by commas and applies an optional pre-coercer to items before they are passed to the final Pydantic validator.
.. code-block:: python
coerce_list("a, b, c") # ["a", "b", "c"]
coerce_list("yes, no", coerce_bool) # [True, False]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | Any | The value to coerce into a list. | required |
item_pre_coercer | Callable[[Any], Any] | None | Optional function to apply to each item. | None |
Returns:
| Type | Description |
|---|---|
list[Any] | A list of processed items. |
Source code in src/gitversioned/utils/pydantic.py
coerce_path(value) ¶
Normalize string paths to Path objects.
.. code-block:: python
coerce_path("/tmp/path ") # Path("/tmp/path")
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | Any | The value to coerce into a path. | required |
Returns:
| Type | Description |
|---|---|
Path | Any | A Path object if the input is a string, otherwise the original value. |