Skip to content

Models

plateforme.core.schema.models

This module provides utilities for managing models, validation and serialization within the Plateforme framework using Pydantic features.

The BaseModel class is the foundational base for all models within the Plateforme framework. It extends Pydantic's BaseModel with additional functionality and integrates with the framework resource and service classes.

The ModelConfig class is a configuration object used to define various settings and behaviors for Plateforme models, such as validation rules and serialization options.

Examples:

>>> from plateforme import BaseModel, Field
...
>>> class FooModel(BaseModel):
...     name: str = Field(
...         ...,
...         unique=True,
...         title='Foo Model',
...         description='Name of the foo instance')
...
>>> class BarModel(BaseModel):
...     name: str = Field(
...         ...,
...         unique=True,
...         title='Bar Model',
...         description='Name of the bar instance',
...     )
...     foo: FooModel | None = Field(title='Foo Reference')
Note

See also the Field function for more information on modeling features.

Model module-attribute

Model = TypeVar('Model', bound='BaseModel')

A type variable for a model class.

ModelType module-attribute

ModelType = Type['BaseModel']

A type alias for a model class.

ModelFieldInfo module-attribute

ModelFieldInfo = FieldInfo['BaseModel']

A type alias for a model field information.

RootModelType module-attribute

RootModelType = Type['RootModel[Any]']

A type alias for a root model class.

DiscriminatedModelType module-attribute

DiscriminatedModelType = Type[
    "DiscriminatedModel[BaseModel]"
]

A type alias for a discriminated model class.

BaseModelConfigDict

Bases: TypedDict

A model class configuration dictionary.

alias instance-attribute

alias: str

The alias name of the model. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. It is inferred from the snake case version of the resolved model identifier.

slug instance-attribute

slug: str

The slug name of the model. It must adhere to a specific SLUG pattern as defined in the framework's regular expressions repository. It is inferred from the pluralized kebab case version of the model identifier.

title instance-attribute

title: str

The human-readable name of the model. It must adhere to a specific TITLE pattern as defined in the framework's regular expressions repository. It is inferred from the titleized version of the model identifier.

str_to_lower instance-attribute

str_to_lower: bool

Whether to convert strings to lowercase. Defaults to False.

str_to_upper instance-attribute

str_to_upper: bool

Whether to convert strings to uppercase. Defaults to False.

str_strip_whitespace instance-attribute

str_strip_whitespace: bool

Whether to strip whitespace from strings. Defaults to False.

str_min_length instance-attribute

str_min_length: int

The minimum length for strings. Defaults to None.

str_max_length instance-attribute

str_max_length: int | None

The maximum length for strings. Defaults to None.

frozen instance-attribute

frozen: bool

Whether to freeze the configuration. Defaults to False.

populate_by_name instance-attribute

populate_by_name: bool

Whether to populate fields by name. Defaults to False.

use_enum_values instance-attribute

use_enum_values: bool

Whether to use enum values. Defaults to False.

validate_assignment instance-attribute

validate_assignment: bool

Whether to validate assignments. Defaults to False.

arbitrary_types_allowed instance-attribute

arbitrary_types_allowed: bool

Whether to allow arbitrary types. Defaults to False.

from_attributes instance-attribute

from_attributes: bool

Whether to set attributes from the configuration. Defaults to False.

loc_by_alias instance-attribute

loc_by_alias: bool

Whether to use the alias for error locs. Defaults to True.

alias_generator instance-attribute

alias_generator: (
    Callable[[str], str] | AliasGenerator | None
)

A callable or alias generator to create aliases for the model. Defaults to None.

ignored_types instance-attribute

ignored_types: tuple[type, ...]

A tuple of types to ignore. Defaults to an empty tuple.

allow_inf_nan instance-attribute

allow_inf_nan: bool

Whether to allow infinity and NaN. Defaults to True.

json_schema_extra instance-attribute

json_schema_extra: JsonSchemaExtraCallable | None

Dictionary of extra JSON schema properties. Defaults to None.

json_encoders instance-attribute

json_encoders: dict[type[object], JsonEncoder] | None

A dictionary of custom JSON encoders for specific types. Defaults to None.

strict instance-attribute

strict: bool

Whether to make the configuration strict. Defaults to False.

revalidate_instances instance-attribute

revalidate_instances: Literal[
    "always", "never", "subclass-instances"
]

When and how to revalidate models and dataclasses during validation. Defaults to never.

ser_json_timedelta instance-attribute

ser_json_timedelta: Literal['iso8601', 'float']

The format of JSON serialized timedeltas. Defaults to iso8601.

ser_json_bytes instance-attribute

ser_json_bytes: Literal['utf8', 'base64']

The encoding of JSON serialized bytes. Defaults to utf8.

ser_json_inf_nan instance-attribute

ser_json_inf_nan: Literal['null', 'constants']

The encoding of JSON serialized infinity and NaN float values. Accepts the string values of 'null' and 'constants'. Defaults to 'null'.

validate_default instance-attribute

validate_default: bool

Whether to validate default values during validation. Defaults to False.

validate_return instance-attribute

validate_return: bool

Whether to validate return values during validation. Defaults to False.

protected_namespaces instance-attribute

protected_namespaces: tuple[str, ...]

A tuple of strings that prevent models to have field which conflict with them. The provided namespaces are added to the internally forbidden and protected ones, model_, resource_, and service_. Defaults to an empty tuple.

hide_input_in_errors instance-attribute

hide_input_in_errors: bool

Whether to hide inputs when printing errors. Defaults to False.

plugin_settings instance-attribute

plugin_settings: dict[str, object] | None

A dictionary of settings for plugins. Defaults to None.

schema_generator instance-attribute

schema_generator: type[Any] | None

A custom core schema generator class to use when generating JSON schemas. Defaults to None.

json_schema_serialization_defaults_required instance-attribute

json_schema_serialization_defaults_required: bool

Whether fields with default values should be marked as required in the serialization schema. Defaults to False.

json_schema_mode_override instance-attribute

json_schema_mode_override: (
    Literal["validation", "serialization"] | None
)

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.

coerce_numbers_to_str instance-attribute

coerce_numbers_to_str: bool

If True, enables automatic coercion of any Number type to str in lax (non-strict) mode. Defaults to False.

regex_engine instance-attribute

regex_engine: Literal['rust-regex', 'python-re']

The regex engine to use for pattern validation. Defaults to rust-regex.

validation_error_cause instance-attribute

validation_error_cause: bool

If True, Python exceptions that were part of a validation failure will be shown as an exception group as a cause. Can be useful for debugging. Defaults to False.

use_attribute_docstrings instance-attribute

use_attribute_docstrings: bool

Whether docstrings of attributes should be used for field descriptions. Defaults to False.

cache_strings instance-attribute

cache_strings: bool | Literal['all', 'keys', 'none']

Whether to cache strings to avoid constructing new Python objects. Enabling this setting should significantly improve validation performance while increasing memory usage slightly. - True or 'all' (default): Cache all strings - 'keys': Cache only dictionary keys - False or 'none': No caching Defaults to True.

ModelConfigDict

Bases: BaseModelConfigDict

A model class configuration dictionary.

alias instance-attribute

alias: str

The alias name of the model. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. It is inferred from the snake case version of the resolved model identifier.

slug instance-attribute

slug: str

The slug name of the model. It must adhere to a specific SLUG pattern as defined in the framework's regular expressions repository. It is inferred from the pluralized kebab case version of the model identifier.

title instance-attribute

title: str

The human-readable name of the model. It must adhere to a specific TITLE pattern as defined in the framework's regular expressions repository. It is inferred from the titleized version of the model identifier.

str_to_lower instance-attribute

str_to_lower: bool

Whether to convert strings to lowercase. Defaults to False.

str_to_upper instance-attribute

str_to_upper: bool

Whether to convert strings to uppercase. Defaults to False.

str_strip_whitespace instance-attribute

str_strip_whitespace: bool

Whether to strip whitespace from strings. Defaults to False.

str_min_length instance-attribute

str_min_length: int

The minimum length for strings. Defaults to None.

str_max_length instance-attribute

str_max_length: int | None

The maximum length for strings. Defaults to None.

frozen instance-attribute

frozen: bool

Whether to freeze the configuration. Defaults to False.

populate_by_name instance-attribute

populate_by_name: bool

Whether to populate fields by name. Defaults to False.

use_enum_values instance-attribute

use_enum_values: bool

Whether to use enum values. Defaults to False.

validate_assignment instance-attribute

validate_assignment: bool

Whether to validate assignments. Defaults to False.

arbitrary_types_allowed instance-attribute

arbitrary_types_allowed: bool

Whether to allow arbitrary types. Defaults to False.

from_attributes instance-attribute

from_attributes: bool

Whether to set attributes from the configuration. Defaults to False.

loc_by_alias instance-attribute

loc_by_alias: bool

Whether to use the alias for error locs. Defaults to True.

alias_generator instance-attribute

alias_generator: (
    Callable[[str], str] | AliasGenerator | None
)

A callable or alias generator to create aliases for the model. Defaults to None.

ignored_types instance-attribute

ignored_types: tuple[type, ...]

A tuple of types to ignore. Defaults to an empty tuple.

allow_inf_nan instance-attribute

allow_inf_nan: bool

Whether to allow infinity and NaN. Defaults to True.

json_schema_extra instance-attribute

json_schema_extra: JsonSchemaExtraCallable | None

Dictionary of extra JSON schema properties. Defaults to None.

json_encoders instance-attribute

json_encoders: dict[type[object], JsonEncoder] | None

A dictionary of custom JSON encoders for specific types. Defaults to None.

strict instance-attribute

strict: bool

Whether to make the configuration strict. Defaults to False.

revalidate_instances instance-attribute

revalidate_instances: Literal[
    "always", "never", "subclass-instances"
]

When and how to revalidate models and dataclasses during validation. Defaults to never.

ser_json_timedelta instance-attribute

ser_json_timedelta: Literal['iso8601', 'float']

The format of JSON serialized timedeltas. Defaults to iso8601.

ser_json_bytes instance-attribute

ser_json_bytes: Literal['utf8', 'base64']

The encoding of JSON serialized bytes. Defaults to utf8.

ser_json_inf_nan instance-attribute

ser_json_inf_nan: Literal['null', 'constants']

The encoding of JSON serialized infinity and NaN float values. Accepts the string values of 'null' and 'constants'. Defaults to 'null'.

validate_default instance-attribute

validate_default: bool

Whether to validate default values during validation. Defaults to False.

validate_return instance-attribute

validate_return: bool

Whether to validate return values during validation. Defaults to False.

protected_namespaces instance-attribute

protected_namespaces: tuple[str, ...]

A tuple of strings that prevent models to have field which conflict with them. The provided namespaces are added to the internally forbidden and protected ones, model_, resource_, and service_. Defaults to an empty tuple.

hide_input_in_errors instance-attribute

hide_input_in_errors: bool

Whether to hide inputs when printing errors. Defaults to False.

plugin_settings instance-attribute

plugin_settings: dict[str, object] | None

A dictionary of settings for plugins. Defaults to None.

schema_generator instance-attribute

schema_generator: type[Any] | None

A custom core schema generator class to use when generating JSON schemas. Defaults to None.

json_schema_serialization_defaults_required instance-attribute

json_schema_serialization_defaults_required: bool

Whether fields with default values should be marked as required in the serialization schema. Defaults to False.

json_schema_mode_override instance-attribute

json_schema_mode_override: (
    Literal["validation", "serialization"] | None
)

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.

coerce_numbers_to_str instance-attribute

coerce_numbers_to_str: bool

If True, enables automatic coercion of any Number type to str in lax (non-strict) mode. Defaults to False.

regex_engine instance-attribute

regex_engine: Literal['rust-regex', 'python-re']

The regex engine to use for pattern validation. Defaults to rust-regex.

validation_error_cause instance-attribute

validation_error_cause: bool

If True, Python exceptions that were part of a validation failure will be shown as an exception group as a cause. Can be useful for debugging. Defaults to False.

use_attribute_docstrings instance-attribute

use_attribute_docstrings: bool

Whether docstrings of attributes should be used for field descriptions. Defaults to False.

cache_strings instance-attribute

cache_strings: bool | Literal['all', 'keys', 'none']

Whether to cache strings to avoid constructing new Python objects. Enabling this setting should significantly improve validation performance while increasing memory usage slightly. - True or 'all' (default): Cache all strings - 'keys': Cache only dictionary keys - False or 'none': No caching Defaults to True.

defer_build instance-attribute

defer_build: bool

Whether to defer model validator and serializer construction until the first model validation. Defaults to False.

extra instance-attribute

extra: Literal['allow', 'ignore', 'forbid']

Extra values to include in this configuration. Defaults to forbid.

ModelConfig

ModelConfig(
    __owner: Any | None = None,
    __defaults: dict[str, Any] | None = None,
    __partial_init: bool = False,
    /,
    **data: Any,
)

Bases: ConfigWrapper

A model class configuration.

Initialize the configuration class with the given data.

Parameters:

Name Type Description Default
__owner Any | None

The owner of the configuration instance. It can be any object or type that uses the configuration instance. Defaults to None.

None
__defaults dict[str, Any] | None

The default values to initialize the configuration instance with. Defaults to None.

None
__partial_init bool

Flag indicating whether to partially initialize the configuration instance. Defaults to False.

False
**data Any

The data as keyword arguments to initialize the configuration instance with.

{}
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def __init__(
    self,
    __owner: Any | None = None,
    __defaults: dict[str, Any] | None = None,
    __partial_init: bool = False,
    /,
    **data: Any,
) -> None:
    """Initialize the configuration class with the given data.

    Args:
        __owner: The owner of the configuration instance. It can be any
            object or type that uses the configuration instance.
            Defaults to ``None``.
        __defaults: The default values to initialize the configuration
            instance with. Defaults to ``None``.
        __partial_init: Flag indicating whether  to partially initialize
            the configuration instance. Defaults to ``False``.
        **data: The data as keyword arguments to initialize the
            configuration instance with.
    """
    # Initialize configuration instance
    self.__config_owner__ = __owner \
        or getattr(self, '__config_owner__', None)
    self.__config_defaults__: dict[str, Any] = __defaults or {}
    with self.context(allow_mutation=True):
        self.update(data)

    # Validate configuration instance
    if not __partial_init:
        self.validate()

type_ class-attribute instance-attribute

type_: str = ConfigField(
    default="model", frozen=True, init=False
)

The configuration owner type set to model. It is a protected field that is typically used with check_config to validate an object type without using isinstance in order to avoid circular imports.

stub class-attribute instance-attribute

stub: bool = ConfigField(
    default=False, frozen=True, init=False
)

Whether the model is a stub model. This is set to True when a collected bare model has a final stub no-operation statement. Defaults to False.

alias class-attribute instance-attribute

alias: str = Deferred

The alias name of the model. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. It is inferred from the snake case version of the resolved model identifier.

slug class-attribute instance-attribute

slug: str = Deferred

The slug name of the model. It must adhere to a specific SLUG pattern as defined in the framework's regular expressions repository. It is inferred from the pluralized kebab case version of the model identifier.

title class-attribute instance-attribute

title: Annotated[str, pydantic] = Deferred

The human-readable name of the model. It must adhere to a specific TITLE pattern as defined in the framework's regular expressions repository. It is inferred from the titleized version of the model identifier.

str_to_lower class-attribute instance-attribute

str_to_lower: Annotated[bool, pydantic] = False

Whether to convert strings to lowercase. Defaults to False.

str_to_upper class-attribute instance-attribute

str_to_upper: Annotated[bool, pydantic] = False

Whether to convert strings to uppercase. Defaults to False.

str_strip_whitespace class-attribute instance-attribute

str_strip_whitespace: Annotated[bool, pydantic] = False

Whether to strip whitespace from strings. Defaults to False.

str_min_length class-attribute instance-attribute

str_min_length: Annotated[int, pydantic] = 0

The minimum length for strings. Defaults to None.

str_max_length class-attribute instance-attribute

str_max_length: Annotated[int | None, pydantic] = None

The maximum length for strings. Defaults to None.

extra class-attribute instance-attribute

extra: Annotated[
    Literal["allow", "ignore", "forbid"], pydantic
] = "forbid"

Extra values to include in this configuration. Defaults to forbid.

frozen class-attribute instance-attribute

frozen: Annotated[bool, pydantic] = False

Whether to freeze the configuration. Defaults to False.

populate_by_name class-attribute instance-attribute

populate_by_name: Annotated[bool, pydantic] = False

Whether to populate fields by name. Defaults to False.

use_enum_values class-attribute instance-attribute

use_enum_values: Annotated[bool, pydantic] = False

Whether to use enum values. Defaults to False.

validate_assignment class-attribute instance-attribute

validate_assignment: Annotated[bool, pydantic] = False

Whether to validate assignments. Defaults to False.

arbitrary_types_allowed class-attribute instance-attribute

arbitrary_types_allowed: Annotated[bool, pydantic] = False

Whether to allow arbitrary types. Defaults to False.

from_attributes class-attribute instance-attribute

from_attributes: Annotated[bool, pydantic] = False

Whether to set attributes from the configuration. Defaults to False.

loc_by_alias class-attribute instance-attribute

loc_by_alias: Annotated[bool, pydantic] = True

Whether to use the alias for error locs. Defaults to True.

alias_generator class-attribute instance-attribute

alias_generator: Annotated[
    Callable[[str], str] | AliasGenerator | None, pydantic
] = to_name_case

A callable or alias generator to create aliases for the model. Defaults to None.

ignored_types class-attribute instance-attribute

ignored_types: Annotated[tuple[type, ...], pydantic] = ()

A tuple of types to ignore. Defaults to an empty tuple.

allow_inf_nan class-attribute instance-attribute

allow_inf_nan: Annotated[bool, pydantic] = True

Whether to allow infinity and NaN. Defaults to True.

json_schema_extra class-attribute instance-attribute

json_schema_extra: Annotated[
    JsonSchemaExtraCallable | None, pydantic
] = None

Dictionary of extra JSON schema properties. Defaults to None.

json_encoders class-attribute instance-attribute

json_encoders: Annotated[
    dict[type[object], JsonEncoder] | None, pydantic
] = None

A dictionary of custom JSON encoders for specific types. Defaults to None.

strict class-attribute instance-attribute

strict: Annotated[bool, pydantic] = False

Whether to make the configuration strict. Defaults to False.

revalidate_instances class-attribute instance-attribute

revalidate_instances: Annotated[
    Literal["always", "never", "subclass-instances"],
    pydantic,
] = "never"

When and how to revalidate models and dataclasses during validation. Defaults to never.

ser_json_timedelta class-attribute instance-attribute

ser_json_timedelta: Annotated[
    Literal["iso8601", "float"], pydantic
] = "iso8601"

The format of JSON serialized timedeltas. Defaults to iso8601.

ser_json_bytes class-attribute instance-attribute

ser_json_bytes: Annotated[
    Literal["utf8", "base64"], pydantic
] = "utf8"

The encoding of JSON serialized bytes. Defaults to utf8.

ser_json_inf_nan class-attribute instance-attribute

ser_json_inf_nan: Annotated[
    Literal["null", "constants"], pydantic
] = "null"

The encoding of JSON serialized infinity and NaN float values. Accepts the string values of 'null' and 'constants'. Defaults to 'null'.

validate_default class-attribute instance-attribute

validate_default: Annotated[bool, pydantic] = False

Whether to validate default values during validation. Defaults to False.

validate_return class-attribute instance-attribute

validate_return: Annotated[bool, pydantic] = False

Whether to validate return values during validation. Defaults to False.

protected_namespaces class-attribute instance-attribute

protected_namespaces: Annotated[
    tuple[str, ...], pydantic
] = Deferred

A tuple of strings that prevent models to have field which conflict with them. The provided namespaces are added to the internally forbidden and protected ones, model_, resource_, and service_. Defaults to an empty tuple.

hide_input_in_errors class-attribute instance-attribute

hide_input_in_errors: Annotated[bool, pydantic] = False

Whether to hide inputs when printing errors. Defaults to False.

defer_build class-attribute instance-attribute

defer_build: Annotated[bool, pydantic] = False

Whether to defer model validator and serializer construction until the first model validation. Defaults to False.

plugin_settings class-attribute instance-attribute

plugin_settings: Annotated[
    dict[str, object] | None, pydantic
] = None

A dictionary of settings for plugins. Defaults to None.

schema_generator class-attribute instance-attribute

schema_generator: Annotated[type[Any] | None, pydantic] = (
    None
)

A custom core schema generator class to use when generating JSON schemas. Defaults to None.

json_schema_serialization_defaults_required class-attribute instance-attribute

json_schema_serialization_defaults_required: Annotated[
    bool, pydantic
] = False

Whether fields with default values should be marked as required in the serialization schema. Defaults to False.

json_schema_mode_override class-attribute instance-attribute

json_schema_mode_override: Annotated[
    Literal["validation", "serialization"] | None, pydantic
] = None

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.

coerce_numbers_to_str class-attribute instance-attribute

coerce_numbers_to_str: Annotated[bool, pydantic] = False

If True, enables automatic coercion of any Number type to str in lax (non-strict) mode. Defaults to False.

regex_engine class-attribute instance-attribute

regex_engine: Annotated[
    Literal["rust-regex", "python-re"], pydantic
] = "rust-regex"

The regex engine to use for pattern validation. Defaults to rust-regex.

validation_error_cause class-attribute instance-attribute

validation_error_cause: Annotated[bool, pydantic] = False

If True, Python exceptions that were part of a validation failure will be shown as an exception group as a cause. Can be useful for debugging. Defaults to False.

use_attribute_docstrings class-attribute instance-attribute

use_attribute_docstrings: Annotated[bool, pydantic] = False

Whether docstrings of attributes should be used for field descriptions. Defaults to False.

cache_strings class-attribute instance-attribute

cache_strings: Annotated[
    bool | Literal["all", "keys", "none"], pydantic
] = True

Whether to cache strings to avoid constructing new Python objects. Enabling this setting should significantly improve validation performance while increasing memory usage slightly. - True or 'all' (default): Cache all strings - 'keys': Cache only dictionary keys - False or 'none': No caching Defaults to True.

create classmethod

create(
    owner: Any | None = None,
    defaults: dict[str, Any] | None = None,
    partial_init: bool = False,
    *,
    data: dict[str, Any] | None = None,
) -> Self

Create a new configuration instance.

This method is typically used internally to create a new configuration class with a specific owner and partial initialization flag. It is an alternative to the __init__ method for creating a new configuration instance.

Parameters:

Name Type Description Default
owner Any | None

The owner of the configuration instance.

None
defaults dict[str, Any] | None

The default values to initialize the configuration instance with. Defaults to None.

None
partial_init bool

Flag indicating whether to partially initialize the configuration instance. Defaults to False.

False
data dict[str, Any] | None

The data to initialize the configuration instance with. Defaults to None.

None

Returns:

Type Description
Self

The new configuration instance created.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
@classmethod
def create(
    cls,
    owner: Any | None = None,
    defaults: dict[str, Any] | None = None,
    partial_init: bool = False,
    *,
    data: dict[str, Any] | None = None,
) -> Self:
    """Create a new configuration instance.

    This method is typically used internally to create a new configuration
    class with a specific owner and partial initialization flag. It is an
    alternative to the `__init__` method for creating a new configuration
    instance.

    Args:
        owner: The owner of the configuration instance.
        defaults: The default values to initialize the configuration
            instance with. Defaults to ``None``.
        partial_init: Flag indicating whether to partially initialize the
            configuration instance. Defaults to ``False``.
        data: The data to initialize the configuration instance with.
            Defaults to ``None``.

    Returns:
        The new configuration instance created.
    """
    return cls(owner, defaults, partial_init, **(data or {}))

from_meta classmethod

from_meta(
    owner: type[Any],
    bases: tuple[type, ...],
    namespace: dict[str, Any],
    /,
    config_attr: str = "__config__",
    partial_init: bool = False,
    data: dict[str, Any] | None = None,
) -> Self

Create a new configuration instance from a class constructor.

This method is typically used internally to create a new configuration class from the meta configuration of a model, package, resource, or service. It merges the configuration of the given bases, the namespace, and the keyword arguments to create a new configuration class.

Parameters:

Name Type Description Default
owner type[Any]

The owner of the configuration instance. It should be the class that is being created from the meta configuration.

required
bases tuple[type, ...]

The configurable base classes to merge.

required
namespace dict[str, Any]

The configurable namespace to merge.

required
config_attr str

The configurable attribute name used to extract the configuration dictionary from the bases and the namespace of the configurable class. Defaults to '__config__'.

'__config__'
partial_init bool

Flag indicating whether to partially initialize the configuration instance. Defaults to False.

False
data dict[str, Any] | None

The data to initialize the configuration instance with. Defaults to None.

None

Returns:

Type Description
Self

The new configuration instance created from the given meta

Self

configuration.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
@classmethod
def from_meta(
    cls,
    owner: type[Any],
    bases: tuple[type, ...],
    namespace: dict[str, Any],
    /,
    config_attr: str = '__config__',
    partial_init: bool = False,
    data: dict[str, Any] | None = None,
) -> Self:
    """Create a new configuration instance from a class constructor.

    This method is typically used internally to create a new configuration
    class from the meta configuration of a model, package, resource, or
    service. It merges the configuration of the given bases, the namespace,
    and the keyword arguments to create a new configuration class.

    Args:
        owner: The owner of the configuration instance. It should be the
            class that is being created from the meta configuration.
        bases: The configurable base classes to merge.
        namespace: The configurable namespace to merge.
        config_attr: The configurable attribute name used to extract the
            configuration dictionary from the bases and the namespace of
            the configurable class. Defaults to ``'__config__'``.
        partial_init: Flag indicating whether to partially initialize the
            configuration instance. Defaults to ``False``.
        data: The data to initialize the configuration instance with.
            Defaults to ``None``.

    Returns:
        The new configuration instance created from the given meta
        configuration.
    """
    with cls.context(allow_mutation=True):
        # Build configuration instance
        config = cls(owner, {}, True)

        for base in bases:
            base_config = getattr(base, config_attr, {})
            if callable(base_config):
                base_config = base_config()
            config.merge(base_config)

        namespace_config = namespace.get(config_attr, {})
        if callable(namespace_config):
            namespace_config = namespace_config()
        config.merge(namespace_config)

        config.merge(data or {})

        # Validate configuration instance
        if not partial_init:
            config.validate()

    return config

validate

validate(
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> None

Validate the configuration instance.

It post-initializes the configuration instance, checks for any missing required fields and validates the assignments of the configuration values based on the configuration fields information and the current validation context. This is performed automatically upon initialization of the configuration instance.

Parameters:

Name Type Description Default
strict bool | None

Whether to enforce strict validation. Defaults to None.

None
context dict[str, Any] | None

The context to use for validation. Defaults to None.

None

Raises:

Type Description
ValueError

If the configuration instance has undefined values for required fields.

ValidationError

If the assignment of a value is invalid based on the configuration fields information and the current validation context.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def validate(
    self,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> None:
    """Validate the configuration instance.

    It post-initializes the configuration instance, checks for any missing
    required fields and validates the assignments of the configuration
    values based on the configuration fields information and the current
    validation context. This is performed automatically upon initialization
    of the configuration instance.

    Args:
        strict: Whether to enforce strict validation. Defaults to ``None``.
        context: The context to use for validation. Defaults to ``None``.

    Raises:
        ValueError: If the configuration instance has undefined values for
            required fields.
        ValidationError: If the assignment of a value is invalid based on
            the configuration fields information and the current validation
            context.
    """
    # Perform post-initialization
    self.post_init()

    # Validate for missing required fields
    config_missing = [
        key for key, field in self.__config_fields__.items()
        if field.is_required() and self[key] is Undefined
    ]
    if config_missing:
        raise ValueError(
            f"Undefined values for configuration "
            f"{self.__class__.__qualname__!r} required fields: "
            f"{', '.join(config_missing)}."
        )

    # Validate assignments
    for key, value in self.entries(scope='set').items():
        if not strict and value is Deferred:
            continue
        if key in self.__config_validators__:
            validator = self.__config_validators__[key].validate_python
            value = validator(value, strict=strict, context=context)
        self.__dict__[key] = value

context staticmethod

context(
    *, allow_mutation: bool | None = None
) -> Iterator[bool]

Context manager for the configuration instance.

If the frozen mutation flag is not specified, the current frozen mutation flag is used if available, otherwise it defaults to False.

Parameters:

Name Type Description Default
allow_mutation bool | None

Flag indicating whether to allow frozen mutation of the configuration instance. When set to False, it prevents any changes by setting the frozen flag to True. If not specified, the current frozen mutation flag is used if available, otherwise it resolves to False. Defaults to None.

None
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
@staticmethod
@contextmanager
def context(
    *, allow_mutation: bool | None = None,
) -> Iterator[bool]:
    """Context manager for the configuration instance.

    If the frozen mutation flag is not specified, the current frozen
    mutation flag is used if available, otherwise it defaults to ``False``.

    Args:
        allow_mutation: Flag indicating whether to allow frozen mutation
            of the configuration instance. When set to ``False``, it
            prevents any changes by setting the frozen flag to ``True``.
            If not specified, the current frozen mutation flag is used if
            available, otherwise it resolves to ``False``.
            Defaults to ``None``.
    """
    context = FROZEN_CONTEXT.get()

    # Set frozen mutation flag
    if allow_mutation is None:
        if context is not None:
            frozen = context
        frozen = True
    else:
        frozen = not allow_mutation

    # Yield and reset frozen mutation flag
    token = FROZEN_CONTEXT.set(frozen)
    try:
        yield frozen
    finally:
        FROZEN_CONTEXT.reset(token)

clear

clear() -> None

Clear the configuration dictionary and reset all values.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def clear(self) -> None:
    """Clear the configuration dictionary and reset all values."""
    for key in self.__config_fields__:
        self.__dict__.pop(key, None)

copy

copy() -> Self

Return a shallow copy of the configuration dictionary.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def copy(self) -> Self:
    """Return a shallow copy of the configuration dictionary."""
    return self.__class__(
        self.__config_owner__,
        self.__config_defaults__.copy(),
        False,
        **self.entries(scope='set')
    )

merge

merge(
    *configs: Self | dict[str, Any],
    setdefault: bool = False,
) -> None

Merge the configuration with other configurations.

It merges the configuration with the provided configuration instances or dictionaries. The precedence of the rightmost configuration is higher than the leftmost configuration. This can be changed by setting the setdefault argument to True.

Parameters:

Name Type Description Default
*configs Self | dict[str, Any]

The configuration instances or dictionaries to merge with the target configuration dictionary.

()
setdefault bool

Flag indicating whether to set the default values for the configuration keys if they are not already set. This modifies the behavior of the merge operation, making the precedence of the leftmost configuration higher than the rightmost configuration. Defaults to False (rightmost precedence).

False
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def merge(
    self,
    *configs: Self | dict[str, Any],
    setdefault: bool = False,
) -> None:
    """Merge the configuration with other configurations.

    It merges the configuration with the provided configuration instances
    or dictionaries. The precedence of the rightmost configuration is
    higher than the leftmost configuration. This can be changed by setting
    the `setdefault` argument to ``True``.

    Args:
        *configs: The configuration instances or dictionaries to merge with
            the target configuration dictionary.
        setdefault: Flag indicating whether to set the default values for
            the configuration keys if they are not already set.
            This modifies the behavior of the merge operation, making the
            precedence of the leftmost configuration higher than the
            rightmost configuration.
            Defaults to ``False`` (rightmost precedence).
    """
    for config in configs:
        # Retrieve the configuration dictionary
        if isinstance(config, self.__class__):
            config_dict = {
                key: value
                for key, value in config.__dict__.items()
                if key in config.__config_fields__
            }
        elif isinstance(config, dict):
            config_dict = config.copy()
        else:
            raise TypeError(
                f"Invalid configuration type {type(config).__name__!r} "
                f"for {self.__class__.__qualname__!r}, it must be a "
                f"dictionary or a configuration instance."
            )
        # Merge with the target configuration dictionary
        if setdefault:
            for key, value in config_dict.items():
                self.setdefault(key, value)
        else:
            self.update(config_dict)

check

check(
    key: str,
    *,
    scope: Literal["all", "default", "set"] = "all",
    raise_errors: bool = True,
) -> bool

Check if the configuration key exists in the given scope.

Parameters:

Name Type Description Default
key str

The configuration key to check for.

required
scope Literal['all', 'default', 'set']

The scope to check for the configuration key. It can be either 'all' to check in all configuration entries, 'default' to check in configuration entries with default values not undefined, or 'set' to check in only the configuration entries that have been explicitly set. Defaults to 'all'.

'all'
raise_errors bool

Flag indicating whether to raise an error if the configuration key is not defined for the configuration wrapper. Defaults to True.

True

Returns:

Type Description
bool

A boolean indicating whether the configuration key exists in the

bool

specified scope.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def check(
    self,
    key: str,
    *,
    scope: Literal['all', 'default', 'set'] = 'all',
    raise_errors: bool = True,
) -> bool:
    """Check if the configuration key exists in the given scope.

    Args:
        key: The configuration key to check for.
        scope: The scope to check for the configuration key. It can be
            either ``'all'`` to check in all configuration entries,
            ``'default'`` to check in configuration entries with default
            values not undefined, or ``'set'`` to check in only the
            configuration entries that have been explicitly set.
            Defaults to ``'all'``.
        raise_errors: Flag indicating whether to raise an error if the
            configuration key is not defined for the configuration wrapper.
            Defaults to ``True``.

    Returns:
        A boolean indicating whether the configuration key exists in the
        specified scope.
    """
    if key not in self.__config_fields__:
        if not raise_errors:
            return False
        raise KeyError(
            f"Configuration key {key!r} cannot be checked as it is not "
            f"defined for wrapper {self.__class__.__qualname__!r}."
        )
    if scope == 'default':
        return key not in self.__dict__
    if scope == 'set':
        return key in self.__dict__
    return True

entries

entries(
    *,
    scope: Literal["all", "default", "set"] = "all",
    default_mode: Literal[
        "preserve", "unwrap", "wrap"
    ] = "unwrap",
    include_keys: Iterable[str] | None = None,
    exclude_keys: Iterable[str] | None = None,
    include_metadata: Iterable[Any] | None = None,
    exclude_metadata: Iterable[Any] | None = None,
) -> dict[str, Any]

Return the configuration dictionary.

It returns the configuration dictionary based on the specified scope, and keys and extra information to filter the configuration dictionary entries.

Parameters:

Name Type Description Default
scope Literal['all', 'default', 'set']

The scope of the configuration dictionary to return. It can be either 'all' to return all configuration entries, 'default' to return all configuration entries with their default values, or 'set' to return only the configuration entries that have been explicitly set. Defaults to 'all'.

'all'
default_mode Literal['preserve', 'unwrap', 'wrap']

The default mode to use when returning a default entry from the configuration dictionary. It can be either 'preserve' to keep the default value as is, 'unwrap' to unwrap the default value, or 'wrap' to wrap the default value with a default placeholder. Defaults to 'unwrap'.

'unwrap'
include_keys Iterable[str] | None

The keys to include from the configuration dictionary entries. Defaults to None.

None
exclude_keys Iterable[str] | None

The keys to exclude from the configuration dictionary entries. Defaults to None.

None
include_metadata Iterable[Any] | None

The metadata information to include from the configuration dictionary entries. Defaults to None.

None
exclude_metadata Iterable[Any] | None

The metadata information to exclude from the configuration dictionary entries. Defaults to None.

None

Returns:

Type Description
dict[str, Any]

A dictionary containing the configuration entries based on the

dict[str, Any]

specified scope and extra information.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def entries(
    self,
    *,
    scope: Literal['all', 'default', 'set'] = 'all',
    default_mode: Literal['preserve', 'unwrap', 'wrap'] = 'unwrap',
    include_keys: Iterable[str] | None = None,
    exclude_keys: Iterable[str] | None = None,
    include_metadata: Iterable[Any] | None = None,
    exclude_metadata: Iterable[Any] | None = None,
) -> dict[str, Any]:
    """Return the configuration dictionary.

    It returns the configuration dictionary based on the specified scope,
    and keys and extra information to filter the configuration dictionary
    entries.

    Args:
        scope: The scope of the configuration dictionary to return. It can
            be either ``'all'`` to return all configuration entries,
            ``'default'`` to return all configuration entries with their
            default values, or ``'set'`` to return only the configuration
            entries that have been explicitly set. Defaults to ``'all'``.
        default_mode: The default mode to use when returning a default
            entry from the configuration dictionary. It can be either
            ``'preserve'`` to keep the default value as is, ``'unwrap'`` to
            unwrap the default value, or ``'wrap'`` to wrap the default
            value with a default placeholder. Defaults to ``'unwrap'``.
        include_keys: The keys to include from the configuration dictionary
            entries. Defaults to ``None``.
        exclude_keys: The keys to exclude from the configuration dictionary
            entries. Defaults to ``None``.
        include_metadata: The metadata information to include from the
            configuration dictionary entries. Defaults to ``None``.
        exclude_metadata: The metadata information to exclude from the
            configuration dictionary entries. Defaults to ``None``.

    Returns:
        A dictionary containing the configuration entries based on the
        specified scope and extra information.
    """
    # Retrieve the configuration dictionary based on the specified scope
    config_dict: dict[str, Any] = {}
    if scope == 'default':
        for key in self.__config_fields__:
            if key in self.__dict__:
                continue
            config_dict[key] = self.get(key, default_mode=default_mode)
    elif scope == 'set':
        for key in self.__config_fields__:
            if key not in self.__dict__:
                continue
            config_dict[key] = self.get(key, default_mode=default_mode)
    else:
        for key in self.__config_fields__:
            config_dict[key] = self.get(key, default_mode=default_mode)

    # Build the keys and metadata sets to include and exclude from the
    # configuration dictionary entries.
    incex_keys = [include_keys, exclude_keys]
    for count, value in enumerate(incex_keys):
        if value is not None:
            if isinstance(value, type) and \
                    issubclass(value, ConfigWrapper):
                value = value.__config_fields__.keys()
            incex_keys[count] = set(value)

    incex_metadata = [include_metadata, exclude_metadata]
    for count, value in enumerate(incex_metadata):
        if value is not None:
            incex_metadata[count] = set(value)

    # Return directly if no keys or metadata filtering is provided.
    if not any(incex_keys) and not any(incex_metadata):
        return config_dict

    # Filter the configuration dictionary based on the information and keys
    # if provided in the "with" arguments.
    for key in list(config_dict.keys()):
        if incex_keys[0] is not None and key not in incex_keys[0]:
            config_dict.pop(key)
        elif incex_keys[1] is not None and key in incex_keys[1]:
            config_dict.pop(key)
        elif incex_metadata[0] is not None and not all(
            metadata in self.__config_fields__[key].metadata
            for metadata in incex_metadata[0]
        ):
            config_dict.pop(key)
        elif incex_metadata[1] is not None and any(
            metadata in self.__config_fields__[key].metadata
            for metadata in incex_metadata[1]
        ):
            config_dict.pop(key)

    return config_dict

keys

keys() -> KeysView[str]

Return the configuration keys.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def keys(self) -> KeysView[str]:
    """Return the configuration keys."""
    return KeysView(self.entries())

values

values() -> ValuesView[Any]

Return the configuration values.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def values(self) -> ValuesView[Any]:
    """Return the configuration values."""
    return ValuesView(self.entries())

items

items() -> ItemsView[str, Any]

Return the configuration items.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def items(self) -> ItemsView[str, Any]:
    """Return the configuration items."""
    return ItemsView(self.entries())

get

get(key: str) -> Any
get(key: str, default: Any) -> Any
get(
    key: str,
    default: Any = Undefined,
    *,
    default_mode: Literal[
        "preserve", "unwrap", "wrap"
    ] = "unwrap",
) -> Any
get(
    key: str,
    default: Any = Undefined,
    *,
    default_mode: Literal[
        "preserve", "unwrap", "wrap"
    ] = "unwrap",
) -> Any

Get the value for the specified key if set otherwise the default.

Parameters:

Name Type Description Default
key str

The configuration key to get the value for.

required
default Any

The default value to return if the key is not set.

Undefined
default_mode Literal['preserve', 'unwrap', 'wrap']

The default mode to use when returning a default value from the configuration dictionary. It can be either 'preserve' to keep the default value as is, 'unwrap' to unwrap the default value, or 'wrap' to wrap the default value with a placeholder. Defaults to 'unwrap'.

'unwrap'
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def get(
    self, key: str,
    default: Any = Undefined,
    *,
    default_mode: Literal['preserve', 'unwrap', 'wrap'] = 'unwrap',
) -> Any:
    """Get the value for the specified key if set otherwise the default.

    Args:
        key: The configuration key to get the value for.
        default: The default value to return if the key is not set.
        default_mode: The default mode to use when returning a default
            value from the configuration dictionary. It can be either
            ``'preserve'`` to keep the default value as is, ``'unwrap'`` to
            unwrap the default value, or ``'wrap'`` to wrap the default
            value with a placeholder. Defaults to ``'unwrap'``.
    """
    if key not in self.__config_fields__:
        raise KeyError(
            f"Configuration key {key!r} cannot be retrieved as it is not "
            f"defined for wrapper {self.__class__.__qualname__!r}."
        )
    if key in self.__dict__:
        return self.__dict__[key]
    if default is Undefined:
        return self.getdefault(key, mode=default_mode)
    if default_mode == 'wrap':
        return Default(default)
    if default_mode == 'unwrap':
        return get_value_or_default(default)
    return default

pop

pop(key: str) -> Any
pop(key: str, default: Any) -> Any
pop(
    key: str,
    default: Any = Undefined,
    *,
    default_mode: Literal[
        "preserve", "unwrap", "wrap"
    ] = "unwrap",
) -> Any
pop(
    key: str,
    default: Any = Undefined,
    *,
    default_mode: Literal[
        "preserve", "unwrap", "wrap"
    ] = "unwrap",
) -> Any

Pop the specified key if set and return its corresponding value.

Parameters:

Name Type Description Default
key str

The configuration key to pop the value for.

required
default Any

The default value to return if the key is not set.

Undefined
default_mode Literal['preserve', 'unwrap', 'wrap']

The default mode to use when returning a default value from the configuration dictionary. It can be either 'preserve' to keep the default value as is, 'unwrap' to unwrap the default value, or 'wrap' to wrap the default value with a placeholder. Defaults to 'unwrap'.

'unwrap'
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def pop(
    self,
    key: str,
    default: Any = Undefined,
    *,
    default_mode: Literal['preserve', 'unwrap', 'wrap'] = 'unwrap',
) -> Any:
    """Pop the specified key if set and return its corresponding value.

    Args:
        key: The configuration key to pop the value for.
        default: The default value to return if the key is not set.
        default_mode: The default mode to use when returning a default
            value from the configuration dictionary. It can be either
            ``'preserve'`` to keep the default value as is, ``'unwrap'`` to
            unwrap the default value, or ``'wrap'`` to wrap the default
            value with a placeholder. Defaults to ``'unwrap'``.
    """
    if key not in self.__config_fields__:
        raise KeyError(
            f"Configuration key {key!r} cannot be popped as it is not "
            f"defined for wrapper {self.__class__.__qualname__!r}."
        )
    if key in self.__dict__:
        return self.__dict__.pop(key)
    if default is Undefined:
        return self.getdefault(key, mode=default_mode)
    if default_mode == 'wrap':
        return Default(default)
    if default_mode == 'unwrap':
        return get_value_or_default(default)
    return default

getdefault

getdefault(
    key: str,
    *,
    mode: Literal["preserve", "unwrap", "wrap"] = "unwrap",
) -> Any

Get the default value for the specified key.

Parameters:

Name Type Description Default
key str

The configuration key to get the default value for.

required
mode Literal['preserve', 'unwrap', 'wrap']

The mode to use when returning the default value. It can be either 'preserve' to keep the default value as is, 'unwrap' to unwrap the default value, or 'wrap' to wrap the default value with a placeholder. Defaults to 'unwrap'.

'unwrap'
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def getdefault(
    self,
    key: str,
    *,
    mode: Literal['preserve', 'unwrap', 'wrap'] = 'unwrap',
) -> Any:
    """Get the default value for the specified key.

    Args:
        key: The configuration key to get the default value for.
        mode: The mode to use when returning the default value. It can be
            either ``'preserve'`` to keep the default value as is,
            ``'unwrap'`` to unwrap the default value, or ``'wrap'`` to wrap
            the default value with a placeholder. Defaults to ``'unwrap'``.
    """
    if key not in self.__config_fields__:
        raise KeyError(
            f"Default for configuration key {key!r} cannot be retrieved "
            f"as it is not defined for wrapper "
            f"{self.__class__.__qualname__!r}."
        )
    elif key in self.__config_defaults__:
        default = self.__config_defaults__[key]
    else:
        default = self.__config_fields__[key].get_default()

    if mode == 'wrap':
        return Default(default)
    if mode == 'unwrap':
        return get_value_or_default(default)
    return default

setdefault

setdefault(key: str, default: Any) -> Any

Set the default value for the specified key.

Parameters:

Name Type Description Default
key str

The configuration key to set the default value for.

required
default Any

The default value to set for the key.

required
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def setdefault(self, key: str, default: Any) -> Any:
    """Set the default value for the specified key.

    Args:
        key: The configuration key to set the default value for.
        default: The default value to set for the key.
    """
    if key not in self.__config_fields__:
        raise KeyError(
            f"Default for configuration key {key!r} cannot be set as it "
            f"is not defined for wrapper {self.__class__.__qualname__!r}."
        )
    self.__config_defaults__[key] = default
    return default

update

update(
    *args: tuple[str, Any] | Mapping[str, Any],
    **kwargs: Any,
) -> None

Update the config dictionary with new data.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def update(
    self,
    *args: tuple[str, Any] | Mapping[str, Any],
    **kwargs: Any,
) -> None:
    """Update the config dictionary with new data."""
    # Helper function to update configuration entries
    def update_entry(key: str, value: Any) -> None:
        if key not in self.__config_fields__:
            raise KeyError(
                f"Configuration key {key!r} cannot be updated as it is "
                f"not defined for wrapper {self.__class__.__qualname__!r}."
            )
        setattr(self, key, value)

    # Update args data
    for arg in args:
        if isinstance(arg, tuple):
            if len(arg) != 2:
                raise ValueError(
                    f"Configuration update arguments must be provided as "
                    f"key-value pairs. Got: {arg}."
                )
            update_entry(arg[0], arg[1])
        else:
            for key, value in arg.items():
                update_entry(key, value)
    # Update kwargs data
    for key, value in kwargs.items():
        update_entry(key, value)

post_init

post_init() -> None

Post-initialization steps for the model configuration.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def post_init(self) -> None:
    """Post-initialization steps for the model configuration."""
    # Validate protected namespaces
    self.setdefault('protected_namespaces', PROTECTED_NAMESPACES)
    if self.check('protected_namespaces', scope='set'):
        self.protected_namespaces = tuple(dict.fromkeys(
            PROTECTED_NAMESPACES + self.protected_namespaces
        ))

    # Skip post-initialization if the configuration owner is not set
    if self.__config_owner__ is None:
        return

    cls_name = self.__config_owner__.__name__
    cls_qualname = self.__config_owner__.__qualname__

    # Validate configuration alias
    self.setdefault('alias', to_name_case(cls_name, ('all', None)))
    if not re.match(RegexPattern.ALIAS, self.alias):
        raise PlateformeError(
            f"The model {cls_qualname!r} has an invalid alias "
            f"{self.alias!r} in its configuration. It must match a "
            f"specific pattern `ALIAS` defined in the framework's regular "
            f"expressions repository.",
            code='model-invalid-config',
        )

    # Validate configuration slug
    self.setdefault('slug', to_path_case(pluralize(self.alias)))
    if not re.match(RegexPattern.SLUG, self.slug):
        raise PlateformeError(
            f"The model {cls_qualname!r} has an invalid slug "
            f"{self.slug!r} in its configuration. It must match a "
            f"specific pattern `SLUG` defined in the framework's regular "
            f"expressions repository.",
            code='model-invalid-config',
        )

    # Validate configuration title
    self.setdefault('title', to_title_case(self.alias))
    if not re.match(RegexPattern.TITLE, self.title):
        raise PlateformeError(
            f"The model {cls_qualname!r} has an invalid title "
            f"{self.title!r} in its configuration. It must match a "
            f"specific pattern `TITLE` defined in the framework's regular "
            f"expressions repository.",
            code='model-invalid-config',
        )

ModelMeta

ModelMeta(
    name: str,
    bases: tuple[type, ...],
    namespace: dict[str, Any],
    /,
    *args: Any,
    **kwargs: Any,
)

Bases: ConfigurableMeta, ModelMetaclass

Meta class for the base model class.

Initialize a new model meta class.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(
    cls,
    name: str,
    bases: tuple[type, ...],
    namespace: dict[str, Any],
    /,
    *args: Any,
    **kwargs: Any,
) -> None:
    """Initialize a new model meta class."""
    # Retrieve field owner
    if cls.__pydantic_owner__ == 'model':
        field_owner = cls
    elif cls.__pydantic_resource__ is not None:
        field_owner = cls.__pydantic_resource__  # type: ignore
    else:
        raise PlateformeError(
            f"THe model fields owner cannot be set to `resource` without "
            f"providing a resource class for the model {name!r}.",
            code='model-invalid-config',
        )

    # Update fields information
    for key, field in cls.model_fields.items():
        cls.model_fields[key] = \
            FieldInfo.from_field_info(field, owner=field_owner, name=key)

    # Check fields for duplicated associations
    for field_a in cls.model_fields.values():
        for field_b in cls.model_fields.values():
            if field_a is field_b:
                continue
            if field_a.linked and field_b.linked \
                    and field_a.target == field_b.target \
                    and field_a.association_alias == \
                        field_b.association_alias:
                raise PlateformeError(
                    f"Link {field_a.alias!r} and {field_b.alias!r} have "
                    f"the same target {field_a.target!r} and association "
                    f"alias {field_a.association_alias!r}.",
                    code='model-invalid-config',
                )

    # Set the model type adapter
    if not kwargs.get('defer_build', False):
        try:
            adapter = TypeAdapterList(cls)
            setattr(cls, '__pydantic_adapter__', adapter)
        except:
            pass

collect_config_wrappers

collect_config_wrappers(
    bases: tuple[type, ...], namespace: dict[str, Any]
) -> list[ConfigType]

Collect configuration wrappers from the given bases and namespace.

It collects the configuration wrappers from the given bases and namespace by extracting the configuration wrapper type from the original bases annotation if it is a generic subclass of the configurable class or metaclass, and from the configuration attribute if present in the class and bases namespace.

Parameters:

Name Type Description Default
bases tuple[type, ...]

The class bases.

required
namespace dict[str, Any]

The class namespace.

required

Returns:

Type Description
list[ConfigType]

A list of configuration wrapper classes found in the given bases

list[ConfigType]

and namespace.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def collect_config_wrappers(
    cls, bases: tuple[type, ...], namespace: dict[str, Any], /,
) -> list[ConfigType]:
    """Collect configuration wrappers from the given bases and namespace.

    It collects the configuration wrappers from the given bases and
    namespace by extracting the configuration wrapper type from the
    original bases annotation if it is a generic subclass of the
    configurable class or metaclass, and from the configuration attribute
    if present in the class and bases namespace.

    Args:
        bases: The class bases.
        namespace: The class namespace.

    Returns:
        A list of configuration wrapper classes found in the given bases
        and namespace.
    """
    config_attr = getattr(cls, '__config_attr__', '__config__')
    config_wrappers: list[ConfigType] = []

    # The collection process is done in two steps to ensure that the
    # configuration attribute is extracted from the annotation first, and
    # then from the class and bases namespace.

    # Extract the configuration wrapper type from the annotation if it is a
    # generic subclass of the configurable class.
    meta_bases = get_meta_orig_bases(bases, namespace)
    for meta_base in meta_bases:
        origin = typing.get_origin(meta_base)
        if origin is None:
            continue
        if not isbaseclass_lenient(origin, 'Configurable'):
            continue
        args = typing.get_args(meta_base)
        if len(args) == 1:
            if isinstance(args[0], TypeVar):
                break
            if issubclass(args[0], ConfigWrapper):
                config_wrappers.append(args[0])
                break
        raise TypeError(
            f"Generic argument for the `Configurable` class must be a "
            f"subclass of the base configuration wrapper. Got: {args}."
        )

    # Extract the configuration wrapper type from the configuration
    # attribute if present in the class and bases namespace.
    meta_namespaces = get_meta_namespaces(bases, namespace)
    for meta_namespace in meta_namespaces:
        if config_attr not in meta_namespace:
            continue
        config_wrapper = meta_namespace[config_attr]
        if callable(config_wrapper):
            config_wrapper = config_wrapper()
        if isinstance(config_wrapper, ConfigWrapper):
            config_wrappers.append(config_wrapper.__class__)
            continue
        if isinstance(config_wrapper, dict):
            continue
        raise TypeError(
            f"Configuration attribute must be a dictionary or an "
            f"instance of the base configuration wrapper. Got: "
            f"{type(config_wrapper).__qualname__}."
        )

    return config_wrappers

BaseModel

BaseModel(**data: Any)

Bases: BaseModel, Configurable[ModelConfig]

Base class for all Plateforme models.

It exposes the base class for all models within the Plateforme framework.

Attributes:

Name Type Description
__config__ ModelConfig | ConfigDict[ModelConfigDict]

The configuration class for the model.

__pydantic_owner__ Literal['model', 'resource']

The owner of the model fields, either the model itself or the resource it belongs to. Defaults to 'model'.

__pydantic_resource__ ResourceType | None

The resource that the model belongs to.

__class_vars__ set[str]

The names of classvars defined on the model.

__private_attributes__ dict[str, ModelPrivateAttr]

Metadata about the private attributes of the model.

__signature__ Signature

The signature for instantiating the model.

__pydantic_complete__ bool

Whether model building is completed, or if there are still undefined fields.

__pydantic_validated__ bool

Whether the model has been validated or directly constructed.

__pydantic_core_schema__ CoreSchema

The pydantic-core schema used to build the SchemaValidator and SchemaSerializer.

__pydantic_custom_init__ bool

Whether the model has a custom __init__ function.

__pydantic_decorators__ DecoratorInfos

Metadata containing the decorators defined on the model.

__pydantic_generic_metadata__ PydanticGenericMetadata

Metadata for generic models, it contains data used for a similar purpose to __args__, __origin__, and __parameters__ in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ dict[str, Any] | None

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ None | Literal['model_post_init']

The name of the post-init method for the model, if defined.

__pydantic_discriminated_model__ bool

Whether the model is an implementation of the DiscriminatedModel class.

__pydantic_root_model__

Whether the model is an implementation of the RootModel class.

__pydantic_adapter__ TypeAdapterList[BaseModel]

The pydantic TypeAdapterList used to validate and serialize collections of instances of the model.

__pydantic_serializer__ SchemaSerializer

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_validator__ SchemaValidator

The pydantic-core SchemaValidator used to validate instances of the model.

__pydantic_extra__ dict[str, Any] | None

An instance attribute with the values of extra fields from validation when resource_config['extra'] == 'allow'.

__pydantic_fields_set__ set[str]

An instance attribute with the names of fields explicitly set.

__pydantic_private__ dict[str, Any] | None

Instance attribute with the values of private attributes set on the model instance.

Initialize a model instance.

It initializes a model instance by parsing and validating input data from the data keyword arguments.

Parameters:

Name Type Description Default
**data Any

The input data to initialize the model instance.

{}

Raises:

Type Description
ValidationError

If the object could not be validated.

Note

The argument self is explicitly positional-only to allow self as a field name and data keyword argument.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

model_extra property

model_extra: dict[str, Any] | None

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

model_fields_set: set[str]

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

model_dump_json

model_dump_json(
    *,
    indent: int | None = None,
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> str

Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
include IncEx

Field(s) to include in the JSON output.

None
exclude IncEx

Field(s) to exclude from the JSON output.

None
by_alias bool

Whether to serialize using field aliases.

False
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool

Whether to log warnings when invalid fields are encountered.

True

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> str:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump_json

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: Whether to log warnings when invalid fields are encountered.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        include=include,
        exclude=exclude,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        round_trip=round_trip,
        warnings=warnings,
    ).decode()

model_parametrized_name classmethod

model_parametrized_name(
    params: tuple[type[Any], ...],
) -> str

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, typing.Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

copy

copy(
    *,
    include: AbstractSetIntStr
    | MappingIntStrAny
    | None = None,
    exclude: AbstractSetIntStr
    | MappingIntStrAny
    | None = None,
    update: Dict[str, Any] | None = None,
    deep: bool = False,
) -> Model

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Model

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self: Model,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: typing.Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Model:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```py
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_adapter

model_adapter() -> TypeAdapterList[BaseModel]

Get the model type adapter.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classproperty
def model_adapter(cls) -> TypeAdapterList['BaseModel']:
    """Get the model type adapter."""
    if not hasattr(cls, '__pydantic_adapter__'):
        raise AttributeError(
            "The model type adapter is not defined. This may be due to "
            "the model not being fully built or an error occurred during "
            "model construction."
        )
    return cls.__pydantic_adapter__

model_construct classmethod

model_construct(
    _fields_set: set[str] | None = None, **data: Any
) -> Model

Creates a new instance of the model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. It behaves as if model_config.extra = 'allow' was set since it adds all passed values.

Parameters:

Name Type Description Default
_fields_set set[str] | None

The set of field names accepted by the model instance.

None
**data Any

Trusted or pre-validated input data to initialize the model. It is used to set the __dict__ attribute of the model.

{}

Returns:

Type Description
Model

A new instance of the model class with validated data.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_construct(  # type: ignore[override, unused-ignore]
    cls: type[Model],
    _fields_set: set[str] | None = None,
    **data: Any,
) -> Model:
    """Creates a new instance of the model class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__`
    from trusted or pre-validated data. Default values are respected, but
    no other validation is performed. It behaves as if
    `model_config.extra = 'allow'` was set since it adds all passed values.

    Args:
        _fields_set: The set of field names accepted by the model instance.
        **data: Trusted or pre-validated input data to initialize the
            model. It is used to set the `__dict__` attribute of the model.

    Returns:
        A new instance of the model class with validated data.
    """
    model = super().model_construct(_fields_set, **data)

    # Remove default initialization of instrumented resource fields, as
    # they are not needed when constructing a resource instance directly,
    # i.e. defaults are already set and stored in the database.
    if cls.__pydantic_owner__ == 'resource':
        resource = cls.__pydantic_resource__
        for name in getattr(resource, 'resource_attributes'):
            if _fields_set and name in _fields_set:
                continue
            model.__dict__.pop(name, None)

    return model

model_copy

model_copy(
    *,
    update: dict[str, Any] | None = None,
    deep: bool = False,
) -> Model

Returns a copy of the model.

Parameters:

Name Type Description Default
update dict[str, Any] | None

Values to add/modify within the new model. Note that if assignment validation is not set to True, the integrity of the data is not validated when creating the new model. Data should be trusted or pre-validated in this case.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Model

A new copy of the model instance with the updated values.

Raises:

Type Description
ValidationError

If the object could not be validated.

ValueError

If strict or context are set when validate_assignment is set to False.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_copy(  # type: ignore[override, unused-ignore]
    self: Model,
    *,
    update: dict[str, Any] | None = None,
    deep: bool = False,
) -> Model:
    """Returns a copy of the model.

    Args:
        update: Values to add/modify within the new model. Note that if
            assignment validation is not set to ``True``, the integrity of
            the data is not validated when creating the new model. Data
            should be trusted or pre-validated in this case.
        deep: Set to ``True`` to make a deep copy of the model.

    Returns:
        A new copy of the model instance with the updated values.

    Raises:
        ValidationError: If the object could not be validated.
        ValueError: If `strict` or `context` are set when
            `validate_assignment` is set to ``False``.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        copied.model_update(update, from_attributes=False)
    return copied

model_dump

model_dump(
    *,
    mode: Literal["json", "python", "raw"] | str = "python",
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> dict[str, Any]

Generate a dictionary representation of the model.

It is used to dump the model instance to a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python', 'raw'] | str

The mode in which to_python should run: - If mode is json, the output will only contain JSON serializable types. - If mode is python, the output may contain non JSON serializable Python objects. - If mode is raw, the output will contain raw values. Defaults to python.

'python'
include IncEx | None

A list of fields to include in the output. Defaults to None.

None
exclude IncEx | None

A list of fields to exclude from the output. Defaults to None.

None
by_alias bool

Whether to use the field's alias in the dictionary key if defined. Defaults to False.

False
exclude_unset bool

Whether to exclude fields that have not been explicitly set. Defaults to False.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value. Defaults to False.

False
exclude_none bool

Whether to exclude fields that have a value of None. Defaults to False.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T]. Defaults to False.

False
warnings bool

Whether to log warnings when invalid fields are encountered. Defaults to True.

True

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_dump(  # type: ignore[override, unused-ignore]
    self,
    *,
    mode: Literal['json', 'python', 'raw'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> dict[str, Any]:
    """Generate a dictionary representation of the model.

    It is used to dump the model instance to a dictionary representation of
    the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run:
            - If mode is ``json``, the output will only contain JSON
                serializable types.
            - If mode is ``python``, the output may contain non JSON
                serializable Python objects.
            - If mode is ``raw``, the output will contain raw values.
            Defaults to ``python``.
        include: A list of fields to include in the output.
            Defaults to ``None``.
        exclude: A list of fields to exclude from the output.
            Defaults to ``None``.
        by_alias: Whether to use the field's alias in the dictionary key if
            defined. Defaults to ``False``.
        exclude_unset: Whether to exclude fields that have not been
            explicitly set. Defaults to ``False``.
        exclude_defaults: Whether to exclude fields that are set to their
            default value. Defaults to ``False``.
        exclude_none: Whether to exclude fields that have a value of
            ``None``. Defaults to ``False``.
        round_trip: If ``True``, dumped values should be valid as input for
            non-idempotent types such as `Json[T]`. Defaults to ``False``.
        warnings: Whether to log warnings when invalid fields are
            encountered. Defaults to ``True``.

    Returns:
        A dictionary representation of the model.
    """
    if mode != 'raw':
        return self.__pydantic_serializer__.to_python(  # type: ignore
            self,
            mode=mode,
            by_alias=by_alias,
            include=include,  # type: ignore
            exclude=exclude,  # type: ignore
            exclude_unset=exclude_unset,
            exclude_defaults=exclude_defaults,
            exclude_none=exclude_none,
            round_trip=round_trip,
            warnings=warnings,
        )

    # Handle raw mode
    result: dict[str, Any] = {}
    for field_name, field_info in self.model_fields.items():
        if not hasattr(self, field_name):
            continue
        value = getattr(self, field_name)
        # Skip excluded fields
        if include is not None and field_name not in include:
            continue
        if exclude is not None and field_name in exclude:
            continue
        if exclude_unset and field_name not in self.model_fields_set:
            continue
        if exclude_defaults and value == field_info.default:
            continue
        if exclude_none and value is None:
            continue
        # Add field value
        if by_alias and field_info.alias:
            result[field_info.alias] = value
        else:
            result[field_name] = value
    return result

model_json_schema classmethod

model_json_schema(
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[
        GenerateJsonSchema
    ] = GenerateJsonSchema,
    mode: JsonSchemaMode = "validation",
    source: JsonSchemaSource = "model",
) -> dict[str, Any]

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use field aliases when generating the schema, i.e. if True, fields will be serialized according to their alias, otherwise according to their attribute name. Defaults to True.

True
ref_template str

The template format string used when generating reference names. Defaults to DEFAULT_REF_TEMPLATE.

DEFAULT_REF_TEMPLATE
schema_generator type[GenerateJsonSchema]

The class to use for generating the JSON Schema.

GenerateJsonSchema
mode JsonSchemaMode

The mode to use for generating the JSON Schema. It can be either validation or serialization where respectively the schema is generated for validating data or serializing data. Defaults to validation.

'validation'
source JsonSchemaSource

The source type to use for generating the resources JSON schema. It can be either key , model, or both where the latter accepts, when applicable, integer and string values for key identifiers in addition to the standard model schema generation. Defaults to model.

'model'

Returns:

Type Description
dict[str, Any]

The generated JSON schema of the model class.

Note

The schema generator class can be overridden to customize the logic used to generate the JSON schema. This can be done by subclassing the GenerateJsonSchema class and passing the subclass as the schema_generator argument.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_json_schema(  # type: ignore[override, unused-ignore]
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    source: JsonSchemaSource = 'model',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use field aliases when generating the schema,
            i.e. if ``True``, fields will be serialized according to their
            alias, otherwise according to their attribute name.
            Defaults to ``True``.
        ref_template: The template format string used when generating
            reference names. Defaults to ``DEFAULT_REF_TEMPLATE``.
        schema_generator: The class to use for generating the JSON Schema.
        mode: The mode to use for generating the JSON Schema. It can be
            either ``validation`` or ``serialization`` where respectively
            the schema is generated for validating data or serializing
            data. Defaults to ``validation``.
        source: The source type to use for generating the resources JSON
            schema. It can be either ``key`` , ``model``, or ``both`` where
            the latter accepts, when applicable, integer and string values
            for key identifiers in addition to the standard model schema
            generation. Defaults to ``model``.

    Returns:
        The generated JSON schema of the model class.

    Note:
        The schema generator class can be overridden to customize the
        logic used to generate the JSON schema. This can be done by
        subclassing the `GenerateJsonSchema` class and passing the subclass
        as the `schema_generator` argument.
    """
    schema_generator_instance = schema_generator(
        by_alias=by_alias, ref_template=ref_template
    )
    if isinstance(cls.__pydantic_validator__, _mock_val_ser.MockValSer):
        cls.__pydantic_validator__.rebuild()
    return schema_generator_instance.generate(
        cls.__pydantic_core_schema__, mode=mode, source=source
    )

model_post_init

model_post_init(__context: Any) -> None

Post-initialization method for the model class.

Override this method to perform additional initialization after the __init__ and model_construct methods have been called. This is useful in scenarios where it is necessary to perform additional initialization steps after the model has been fully initialized.

Parameters:

Name Type Description Default
__context Any

The context object passed to the model instance.

required
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_post_init(self, __context: Any) -> None:
    """Post-initialization method for the model class.

    Override this method to perform additional initialization after the
    `__init__` and `model_construct` methods have been called. This is
    useful in scenarios where it is necessary to perform additional
    initialization steps after the model has been fully initialized.

    Args:
        __context: The context object passed to the model instance.
    """
    ...

model_rebuild classmethod

model_rebuild(
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: dict[str, Any] | None = None,
) -> bool | None

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema. Defaults to False.

False
raise_errors bool

Whether to raise errors or fail silently. Defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace. Defaults to 2.

2
_types_namespace dict[str, Any] | None

The types namespace. Defaults to None.

None

Raises:

Type Description
PlateformeError

If an error occurred while rebuilding the model adapter and raise_errors is set to True.

PydanticUndefinedAnnotation

If PydanticUndefinedAnnotation occurs in__get_pydantic_core_schema__ and raise_errors is set to True.

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding

bool | None

was not required. If rebuilding was required, returns True if

bool | None

rebuilding was successful, otherwise False if an error

bool | None

occurred and raise_errors is set to False.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_rebuild(  # type: ignore[override, unused-ignore]
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: dict[str, Any] | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a `ForwardRef`
    which could not be resolved during the initial attempt to build the
    schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema.
            Defaults to ``False``.
        raise_errors: Whether to raise errors or fail silently.
            Defaults to ``True``.
        _parent_namespace_depth: The depth level of the parent namespace.
            Defaults to 2.
        _types_namespace: The types namespace. Defaults to ``None``.

    Raises:
        PlateformeError: If an error occurred while rebuilding the model
            adapter and `raise_errors` is set to ``True``.
        PydanticUndefinedAnnotation: If `PydanticUndefinedAnnotation`
            occurs in`__get_pydantic_core_schema__` and `raise_errors` is
            set to ``True``.

    Returns:
        Returns ``None`` if the schema is already "complete" and rebuilding
        was not required. If rebuilding was required, returns ``True`` if
        rebuilding was successful, otherwise ``False`` if an error
        occurred and `raise_errors` is set to ``False``.
    """
    build_status: bool | None = None

    # Rebuild model
    build_status = super().model_rebuild(
        force=build_status or force,
        raise_errors=raise_errors,
        _parent_namespace_depth=_parent_namespace_depth,
        _types_namespace=_types_namespace,
    )

    # Rebuild model adapter
    if build_status:
        try:
            adapter = TypeAdapterList(cls)
            setattr(cls, '__pydantic_adapter__', adapter)
        except Exception as error:
            if not raise_errors:
                return False
            raise PlateformeError(
                f"Failed to rebuild model adapter for {cls.__name__!r}.",
                code='model-build-failed',
            )

    if build_status is not False:
        cls.model_config.pop('defer_build')

    return build_status

model_revalidate

model_revalidate(
    *,
    force: bool = False,
    raise_errors: bool = True,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> bool | None

Revalidate the model instance.

It revalidates the model instance in place, enforcing the types strictly if specified. If the model instance has already been validated, it will not be revalidated unless the force argument is set to True.

Parameters:

Name Type Description Default
force bool

Whether to force the revalidation of the model instance. Defaults to False.

False
raise_errors bool

Whether to raise errors or fail silently. Defaults to True.

True
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Raises:

Type Description
ValidationError

If the model instance could not be validated and raise_errors is set to True.

Returns:

Type Description
bool | None

Returns None if the model instance is already "validated" and

bool | None

revalidation was not required. If validation was required, returns

bool | None

True if validation was successful, otherwise False if an

bool | None

error occurred and raise_errors is set to False.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_revalidate(
    self,
    *,
    force: bool = False,
    raise_errors: bool = True,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> bool | None:
    """Revalidate the model instance.

    It revalidates the model instance in place, enforcing the types
    strictly if specified. If the model instance has already been
    validated, it will not be revalidated unless the `force` argument is
    set to ``True``.

    Args:
        force: Whether to force the revalidation of the model instance.
            Defaults to ``False``.
        raise_errors: Whether to raise errors or fail silently.
            Defaults to ``True``.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Raises:
        ValidationError: If the model instance could not be validated and
            `raise_errors` is set to ``True``.

    Returns:
        Returns ``None`` if the model instance is already "validated" and
        revalidation was not required. If validation was required, returns
        ``True`` if validation was successful, otherwise ``False`` if an
        error occurred and `raise_errors` is set to ``False``.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    if not force and self.__pydantic_validated__:
        return None
    else:
        try:
            self.__pydantic_validated__ = False
            self.__pydantic_validator__.validate_python(
                self,
                strict=strict,
                from_attributes=True,
                context=context,
                self_instance=self,
            )
        except Exception as error:
            if raise_errors:
                raise error
            return False
        return True

model_update

model_update(
    obj: Any,
    *,
    update: dict[str, Any] | None = None,
    from_attributes: bool | None = None,
) -> None

Update the model with the given object and update dictionary.

Parameters:

Name Type Description Default
obj Any

The object to update the model with. It can be a dictionary or an object with attributes (if from_attributes is set to True). If it is a dictionary, the keys must match the model field names if extra fields are not allowed.

required
update dict[str, Any] | None

Values to add/modify within the model. Note that if assignment validation is not set to True, the integrity of the data is not validated when updating the model. Data should be trusted or pre-validated in this case. Defaults to None.

None
from_attributes bool | None

Whether to extract data from object attributes. Defaults to None.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

ValueError

If strict or context are set when validate_assignment is set to False.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_update(
    self,
    obj: Any,
    *,
    update: dict[str, Any] | None = None,
    from_attributes: bool | None = None,
) -> None:
    """Update the model with the given object and update dictionary.

    Args:
        obj: The object to update the model with. It can be a dictionary
            or an object with attributes (if `from_attributes` is set to
            ``True``). If it is a dictionary, the keys must match the model
            field names if extra fields are not allowed.
        update: Values to add/modify within the model. Note that if
            assignment validation is not set to ``True``, the integrity of
            the data is not validated when updating the model. Data should
            be trusted or pre-validated in this case. Defaults to ``None``.
        from_attributes: Whether to extract data from object attributes.
            Defaults to ``None``.

    Raises:
        ValidationError: If the object could not be validated.
        ValueError: If `strict` or `context` are set when
            `validate_assignment` is set to ``False``.
    """
    # Collect update
    update = (update or {}).copy()
    if from_attributes:
        for field_name in self.model_fields:
            if hasattr(obj, field_name):
                update.setdefault(field_name, getattr(obj, field_name))
    elif isinstance(obj, dict):
        update = {**obj, **update}

    # Process update
    for key, value in update.items():
        if key in self.model_fields:
            self.__dict__[key] = value
        else:
            if self.model_config.extra == 'allow':
                if self.__pydantic_extra__ is None:
                    self.__pydantic_extra__ = {}
                self.__pydantic_extra__[key] = value
            elif self.model_config.extra == 'ignore':
                self.__dict__[key] = value
            else:
                raise ValueError(
                    f"Extra field {key!r} is not permitted on the "
                    f"model {self.__class__.__qualname__!r}."
                )

    # Update fields set
    self.__pydantic_fields_set__.update(update.keys())

model_validate classmethod

model_validate(
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate the given object against the model.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
from_attributes bool | None

Whether to extract data from the object attributes.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

A validated model instance.

Raises:

Type Description
ValidationError

If the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate(  # type: ignore[override, unused-ignore]
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate the given object against the model.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        from_attributes: Whether to extract data from the object
            attributes.
        context: Extra variables to pass to the validator.

    Returns:
        A validated model instance.

    Raises:
        ValidationError: If the object could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.__pydantic_validator__.validate_python(  # type: ignore
        obj,
        strict=strict,
        from_attributes=from_attributes,
        context=context,
    )

model_validate_many classmethod

model_validate_many(
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]

Validate the given object collection against the model.

Parameters:

Name Type Description Default
obj Any

The object collection to validate.

required
strict bool | None

Whether to enforce types strictly.

None
from_attributes bool | None

Whether to extract data from the object collection items attributes.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Sequence[Model]

A validated collection of model instances.

Raises:

Type Description
ValidationError

If the object collection could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_many(
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]:
    """Validate the given object collection against the model.

    Args:
        obj: The object collection to validate.
        strict: Whether to enforce types strictly.
        from_attributes: Whether to extract data from the object
            collection items attributes.
        context: Extra variables to pass to the validator.

    Returns:
        A validated collection of model instances.

    Raises:
        ValidationError: If the object collection could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.model_adapter.validate_python(  # type: ignore
        obj,
        strict=strict,
        from_attributes=from_attributes,
        context=context,
    )

model_validate_json classmethod

model_validate_json(
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate the given JSON data against the model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

A validated model instance.

Raises:

Type Description
ValueError

If json_data is not a JSON string.

ValidationError

If the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_json(  # type: ignore[override, unused-ignore]
    cls: type[Model],
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate the given JSON data against the model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        A validated model instance.

    Raises:
        ValueError: If `json_data` is not a JSON string.
        ValidationError: If the object could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.__pydantic_validator__.validate_json(  # type: ignore
        json_data, strict=strict, context=context
    )

model_validate_json_many classmethod

model_validate_json_many(
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]

Validate the given JSON data collection against the model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data collection to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Sequence[Model]

A validated collection of model instances.

Raises:

Type Description
ValueError

If json_data is not a JSON string.

ValidationError

If the object collection could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_json_many(
    cls: type[Model],
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]:
    """Validate the given JSON data collection against the model.

    Args:
        json_data: The JSON data collection to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        A validated collection of model instances.

    Raises:
        ValueError: If `json_data` is not a JSON string.
        ValidationError: If the object collection could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.model_adapter.validate_json(  # type: ignore
        json_data, strict=strict, context=context
    )

model_validate_strings classmethod

model_validate_strings(
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate the given string object against the model.

Parameters:

Name Type Description Default
obj Any

The string object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

A validated model instance.

Raises:

Type Description
ValidationError

If the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_strings(  # type: ignore[override, unused-ignore]
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate the given string object against the model.

    Args:
        obj: The string object to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        A validated model instance.

    Raises:
        ValidationError: If the object could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.__pydantic_validator__.validate_strings(  # type: ignore
        obj, strict=strict, context=context
    )

model_validate_strings_many classmethod

model_validate_strings_many(
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]

Validate the given string object collection against the model.

Parameters:

Name Type Description Default
obj Any

The string object collection to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Sequence[Model]

A validated collection of model instances.

Raises:

Type Description
ValidationError

If the object collection could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_strings_many(
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]:
    """Validate the given string object collection against the model.

    Args:
        obj: The string object collection to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        A validated collection of model instances.

    Raises:
        ValidationError: If the object collection could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.model_adapter.validate_strings(  # type: ignore
        obj, strict=strict, context=context
    )

RootModelMeta

RootModelMeta(
    name: str,
    bases: tuple[type, ...],
    namespace: dict[str, Any],
    /,
    *args: Any,
    **kwargs: Any,
)

Bases: ModelMeta

A metaclass for root model classes.

Initialize a new model meta class.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(
    cls,
    name: str,
    bases: tuple[type, ...],
    namespace: dict[str, Any],
    /,
    *args: Any,
    **kwargs: Any,
) -> None:
    """Initialize a new model meta class."""
    # Retrieve field owner
    if cls.__pydantic_owner__ == 'model':
        field_owner = cls
    elif cls.__pydantic_resource__ is not None:
        field_owner = cls.__pydantic_resource__  # type: ignore
    else:
        raise PlateformeError(
            f"THe model fields owner cannot be set to `resource` without "
            f"providing a resource class for the model {name!r}.",
            code='model-invalid-config',
        )

    # Update fields information
    for key, field in cls.model_fields.items():
        cls.model_fields[key] = \
            FieldInfo.from_field_info(field, owner=field_owner, name=key)

    # Check fields for duplicated associations
    for field_a in cls.model_fields.values():
        for field_b in cls.model_fields.values():
            if field_a is field_b:
                continue
            if field_a.linked and field_b.linked \
                    and field_a.target == field_b.target \
                    and field_a.association_alias == \
                        field_b.association_alias:
                raise PlateformeError(
                    f"Link {field_a.alias!r} and {field_b.alias!r} have "
                    f"the same target {field_a.target!r} and association "
                    f"alias {field_a.association_alias!r}.",
                    code='model-invalid-config',
                )

    # Set the model type adapter
    if not kwargs.get('defer_build', False):
        try:
            adapter = TypeAdapterList(cls)
            setattr(cls, '__pydantic_adapter__', adapter)
        except:
            pass

collect_config_wrappers

collect_config_wrappers(
    bases: tuple[type, ...], namespace: dict[str, Any]
) -> list[ConfigType]

Collect configuration wrappers from the given bases and namespace.

It collects the configuration wrappers from the given bases and namespace by extracting the configuration wrapper type from the original bases annotation if it is a generic subclass of the configurable class or metaclass, and from the configuration attribute if present in the class and bases namespace.

Parameters:

Name Type Description Default
bases tuple[type, ...]

The class bases.

required
namespace dict[str, Any]

The class namespace.

required

Returns:

Type Description
list[ConfigType]

A list of configuration wrapper classes found in the given bases

list[ConfigType]

and namespace.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def collect_config_wrappers(
    cls, bases: tuple[type, ...], namespace: dict[str, Any], /,
) -> list[ConfigType]:
    """Collect configuration wrappers from the given bases and namespace.

    It collects the configuration wrappers from the given bases and
    namespace by extracting the configuration wrapper type from the
    original bases annotation if it is a generic subclass of the
    configurable class or metaclass, and from the configuration attribute
    if present in the class and bases namespace.

    Args:
        bases: The class bases.
        namespace: The class namespace.

    Returns:
        A list of configuration wrapper classes found in the given bases
        and namespace.
    """
    config_attr = getattr(cls, '__config_attr__', '__config__')
    config_wrappers: list[ConfigType] = []

    # The collection process is done in two steps to ensure that the
    # configuration attribute is extracted from the annotation first, and
    # then from the class and bases namespace.

    # Extract the configuration wrapper type from the annotation if it is a
    # generic subclass of the configurable class.
    meta_bases = get_meta_orig_bases(bases, namespace)
    for meta_base in meta_bases:
        origin = typing.get_origin(meta_base)
        if origin is None:
            continue
        if not isbaseclass_lenient(origin, 'Configurable'):
            continue
        args = typing.get_args(meta_base)
        if len(args) == 1:
            if isinstance(args[0], TypeVar):
                break
            if issubclass(args[0], ConfigWrapper):
                config_wrappers.append(args[0])
                break
        raise TypeError(
            f"Generic argument for the `Configurable` class must be a "
            f"subclass of the base configuration wrapper. Got: {args}."
        )

    # Extract the configuration wrapper type from the configuration
    # attribute if present in the class and bases namespace.
    meta_namespaces = get_meta_namespaces(bases, namespace)
    for meta_namespace in meta_namespaces:
        if config_attr not in meta_namespace:
            continue
        config_wrapper = meta_namespace[config_attr]
        if callable(config_wrapper):
            config_wrapper = config_wrapper()
        if isinstance(config_wrapper, ConfigWrapper):
            config_wrappers.append(config_wrapper.__class__)
            continue
        if isinstance(config_wrapper, dict):
            continue
        raise TypeError(
            f"Configuration attribute must be a dictionary or an "
            f"instance of the base configuration wrapper. Got: "
            f"{type(config_wrapper).__qualname__}."
        )

    return config_wrappers

RootModel

RootModel(root: _TRoot = Undefined, **data: Any)

Bases: BaseModel, Generic[_TRoot]

A root model class.

A model used to store a single root object.

a specialized model class used to define and validate a single root object. It's particularly useful for scenarios involving a top-level data structure that doesn't fit neatly into a typical dictionary or list format. The roo model ensures type safety and data validation for this singular, primary object, and allows dynamic type updates without losing references within other models.

Attributes:

Name Type Description
root _TRoot

The root object of the model.

Initialize a root model instance.

It initializes a model instance by parsing and validating input data from the root argument or data keyword arguments.

Parameters:

Name Type Description Default
root _TRoot

The root object of the model.

Undefined
**data Any

The input data to initialize the model instance.

{}

Raises:

Type Description
ValidationError

If the object could not be validated.

Note

The argument self is explicitly positional-only to allow self as a field name and data keyword argument.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, root: _TRoot = Undefined, **data: Any) -> None:
    """Initialize a root model instance.

    It initializes a model instance by parsing and validating input data
    from the `root` argument or `data` keyword arguments.

    Args:
        root: The root object of the model.
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    if data:
        if root is not Undefined:
            raise ValueError(
                f"Root model `__init__` accepts either a single "
                f"positional argument or arbitrary keyword arguments. "
                f"Got both: root={root!r}, data={data!r}"
            )
        root = data  # type: ignore

    self.__pydantic_validator__.validate_python(root, self_instance=self)

model_extra property

model_extra: dict[str, Any] | None

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

model_fields_set: set[str]

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

model_copy

model_copy(
    *,
    update: dict[str, Any] | None = None,
    deep: bool = False,
) -> Model

Returns a copy of the model.

Parameters:

Name Type Description Default
update dict[str, Any] | None

Values to add/modify within the new model. Note that if assignment validation is not set to True, the integrity of the data is not validated when creating the new model. Data should be trusted or pre-validated in this case.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Model

A new copy of the model instance with the updated values.

Raises:

Type Description
ValidationError

If the object could not be validated.

ValueError

If strict or context are set when validate_assignment is set to False.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_copy(  # type: ignore[override, unused-ignore]
    self: Model,
    *,
    update: dict[str, Any] | None = None,
    deep: bool = False,
) -> Model:
    """Returns a copy of the model.

    Args:
        update: Values to add/modify within the new model. Note that if
            assignment validation is not set to ``True``, the integrity of
            the data is not validated when creating the new model. Data
            should be trusted or pre-validated in this case.
        deep: Set to ``True`` to make a deep copy of the model.

    Returns:
        A new copy of the model instance with the updated values.

    Raises:
        ValidationError: If the object could not be validated.
        ValueError: If `strict` or `context` are set when
            `validate_assignment` is set to ``False``.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        copied.model_update(update, from_attributes=False)
    return copied

model_dump_json

model_dump_json(
    *,
    indent: int | None = None,
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> str

Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
include IncEx

Field(s) to include in the JSON output.

None
exclude IncEx

Field(s) to exclude from the JSON output.

None
by_alias bool

Whether to serialize using field aliases.

False
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool

Whether to log warnings when invalid fields are encountered.

True

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> str:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump_json

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: Whether to log warnings when invalid fields are encountered.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        include=include,
        exclude=exclude,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        round_trip=round_trip,
        warnings=warnings,
    ).decode()

model_json_schema classmethod

model_json_schema(
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[
        GenerateJsonSchema
    ] = GenerateJsonSchema,
    mode: JsonSchemaMode = "validation",
    source: JsonSchemaSource = "model",
) -> dict[str, Any]

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use field aliases when generating the schema, i.e. if True, fields will be serialized according to their alias, otherwise according to their attribute name. Defaults to True.

True
ref_template str

The template format string used when generating reference names. Defaults to DEFAULT_REF_TEMPLATE.

DEFAULT_REF_TEMPLATE
schema_generator type[GenerateJsonSchema]

The class to use for generating the JSON Schema.

GenerateJsonSchema
mode JsonSchemaMode

The mode to use for generating the JSON Schema. It can be either validation or serialization where respectively the schema is generated for validating data or serializing data. Defaults to validation.

'validation'
source JsonSchemaSource

The source type to use for generating the resources JSON schema. It can be either key , model, or both where the latter accepts, when applicable, integer and string values for key identifiers in addition to the standard model schema generation. Defaults to model.

'model'

Returns:

Type Description
dict[str, Any]

The generated JSON schema of the model class.

Note

The schema generator class can be overridden to customize the logic used to generate the JSON schema. This can be done by subclassing the GenerateJsonSchema class and passing the subclass as the schema_generator argument.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_json_schema(  # type: ignore[override, unused-ignore]
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    source: JsonSchemaSource = 'model',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use field aliases when generating the schema,
            i.e. if ``True``, fields will be serialized according to their
            alias, otherwise according to their attribute name.
            Defaults to ``True``.
        ref_template: The template format string used when generating
            reference names. Defaults to ``DEFAULT_REF_TEMPLATE``.
        schema_generator: The class to use for generating the JSON Schema.
        mode: The mode to use for generating the JSON Schema. It can be
            either ``validation`` or ``serialization`` where respectively
            the schema is generated for validating data or serializing
            data. Defaults to ``validation``.
        source: The source type to use for generating the resources JSON
            schema. It can be either ``key`` , ``model``, or ``both`` where
            the latter accepts, when applicable, integer and string values
            for key identifiers in addition to the standard model schema
            generation. Defaults to ``model``.

    Returns:
        The generated JSON schema of the model class.

    Note:
        The schema generator class can be overridden to customize the
        logic used to generate the JSON schema. This can be done by
        subclassing the `GenerateJsonSchema` class and passing the subclass
        as the `schema_generator` argument.
    """
    schema_generator_instance = schema_generator(
        by_alias=by_alias, ref_template=ref_template
    )
    if isinstance(cls.__pydantic_validator__, _mock_val_ser.MockValSer):
        cls.__pydantic_validator__.rebuild()
    return schema_generator_instance.generate(
        cls.__pydantic_core_schema__, mode=mode, source=source
    )

model_parametrized_name classmethod

model_parametrized_name(
    params: tuple[type[Any], ...],
) -> str

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, typing.Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init

model_post_init(__context: Any) -> None

Post-initialization method for the model class.

Override this method to perform additional initialization after the __init__ and model_construct methods have been called. This is useful in scenarios where it is necessary to perform additional initialization steps after the model has been fully initialized.

Parameters:

Name Type Description Default
__context Any

The context object passed to the model instance.

required
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_post_init(self, __context: Any) -> None:
    """Post-initialization method for the model class.

    Override this method to perform additional initialization after the
    `__init__` and `model_construct` methods have been called. This is
    useful in scenarios where it is necessary to perform additional
    initialization steps after the model has been fully initialized.

    Args:
        __context: The context object passed to the model instance.
    """
    ...

model_rebuild classmethod

model_rebuild(
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: dict[str, Any] | None = None,
) -> bool | None

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema. Defaults to False.

False
raise_errors bool

Whether to raise errors or fail silently. Defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace. Defaults to 2.

2
_types_namespace dict[str, Any] | None

The types namespace. Defaults to None.

None

Raises:

Type Description
PlateformeError

If an error occurred while rebuilding the model adapter and raise_errors is set to True.

PydanticUndefinedAnnotation

If PydanticUndefinedAnnotation occurs in__get_pydantic_core_schema__ and raise_errors is set to True.

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding

bool | None

was not required. If rebuilding was required, returns True if

bool | None

rebuilding was successful, otherwise False if an error

bool | None

occurred and raise_errors is set to False.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_rebuild(  # type: ignore[override, unused-ignore]
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: dict[str, Any] | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a `ForwardRef`
    which could not be resolved during the initial attempt to build the
    schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema.
            Defaults to ``False``.
        raise_errors: Whether to raise errors or fail silently.
            Defaults to ``True``.
        _parent_namespace_depth: The depth level of the parent namespace.
            Defaults to 2.
        _types_namespace: The types namespace. Defaults to ``None``.

    Raises:
        PlateformeError: If an error occurred while rebuilding the model
            adapter and `raise_errors` is set to ``True``.
        PydanticUndefinedAnnotation: If `PydanticUndefinedAnnotation`
            occurs in`__get_pydantic_core_schema__` and `raise_errors` is
            set to ``True``.

    Returns:
        Returns ``None`` if the schema is already "complete" and rebuilding
        was not required. If rebuilding was required, returns ``True`` if
        rebuilding was successful, otherwise ``False`` if an error
        occurred and `raise_errors` is set to ``False``.
    """
    build_status: bool | None = None

    # Rebuild model
    build_status = super().model_rebuild(
        force=build_status or force,
        raise_errors=raise_errors,
        _parent_namespace_depth=_parent_namespace_depth,
        _types_namespace=_types_namespace,
    )

    # Rebuild model adapter
    if build_status:
        try:
            adapter = TypeAdapterList(cls)
            setattr(cls, '__pydantic_adapter__', adapter)
        except Exception as error:
            if not raise_errors:
                return False
            raise PlateformeError(
                f"Failed to rebuild model adapter for {cls.__name__!r}.",
                code='model-build-failed',
            )

    if build_status is not False:
        cls.model_config.pop('defer_build')

    return build_status

model_validate classmethod

model_validate(
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate the given object against the model.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
from_attributes bool | None

Whether to extract data from the object attributes.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

A validated model instance.

Raises:

Type Description
ValidationError

If the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate(  # type: ignore[override, unused-ignore]
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate the given object against the model.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        from_attributes: Whether to extract data from the object
            attributes.
        context: Extra variables to pass to the validator.

    Returns:
        A validated model instance.

    Raises:
        ValidationError: If the object could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.__pydantic_validator__.validate_python(  # type: ignore
        obj,
        strict=strict,
        from_attributes=from_attributes,
        context=context,
    )

model_validate_json classmethod

model_validate_json(
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate the given JSON data against the model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

A validated model instance.

Raises:

Type Description
ValueError

If json_data is not a JSON string.

ValidationError

If the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_json(  # type: ignore[override, unused-ignore]
    cls: type[Model],
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate the given JSON data against the model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        A validated model instance.

    Raises:
        ValueError: If `json_data` is not a JSON string.
        ValidationError: If the object could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.__pydantic_validator__.validate_json(  # type: ignore
        json_data, strict=strict, context=context
    )

model_validate_strings classmethod

model_validate_strings(
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate the given string object against the model.

Parameters:

Name Type Description Default
obj Any

The string object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

A validated model instance.

Raises:

Type Description
ValidationError

If the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_strings(  # type: ignore[override, unused-ignore]
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate the given string object against the model.

    Args:
        obj: The string object to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        A validated model instance.

    Raises:
        ValidationError: If the object could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.__pydantic_validator__.validate_strings(  # type: ignore
        obj, strict=strict, context=context
    )

copy

copy(
    *,
    include: AbstractSetIntStr
    | MappingIntStrAny
    | None = None,
    exclude: AbstractSetIntStr
    | MappingIntStrAny
    | None = None,
    update: Dict[str, Any] | None = None,
    deep: bool = False,
) -> Model

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Model

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self: Model,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: typing.Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Model:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```py
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_adapter

model_adapter() -> TypeAdapterList[BaseModel]

Get the model type adapter.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classproperty
def model_adapter(cls) -> TypeAdapterList['BaseModel']:
    """Get the model type adapter."""
    if not hasattr(cls, '__pydantic_adapter__'):
        raise AttributeError(
            "The model type adapter is not defined. This may be due to "
            "the model not being fully built or an error occurred during "
            "model construction."
        )
    return cls.__pydantic_adapter__

model_revalidate

model_revalidate(
    *,
    force: bool = False,
    raise_errors: bool = True,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> bool | None

Revalidate the model instance.

It revalidates the model instance in place, enforcing the types strictly if specified. If the model instance has already been validated, it will not be revalidated unless the force argument is set to True.

Parameters:

Name Type Description Default
force bool

Whether to force the revalidation of the model instance. Defaults to False.

False
raise_errors bool

Whether to raise errors or fail silently. Defaults to True.

True
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Raises:

Type Description
ValidationError

If the model instance could not be validated and raise_errors is set to True.

Returns:

Type Description
bool | None

Returns None if the model instance is already "validated" and

bool | None

revalidation was not required. If validation was required, returns

bool | None

True if validation was successful, otherwise False if an

bool | None

error occurred and raise_errors is set to False.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_revalidate(
    self,
    *,
    force: bool = False,
    raise_errors: bool = True,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> bool | None:
    """Revalidate the model instance.

    It revalidates the model instance in place, enforcing the types
    strictly if specified. If the model instance has already been
    validated, it will not be revalidated unless the `force` argument is
    set to ``True``.

    Args:
        force: Whether to force the revalidation of the model instance.
            Defaults to ``False``.
        raise_errors: Whether to raise errors or fail silently.
            Defaults to ``True``.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Raises:
        ValidationError: If the model instance could not be validated and
            `raise_errors` is set to ``True``.

    Returns:
        Returns ``None`` if the model instance is already "validated" and
        revalidation was not required. If validation was required, returns
        ``True`` if validation was successful, otherwise ``False`` if an
        error occurred and `raise_errors` is set to ``False``.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    if not force and self.__pydantic_validated__:
        return None
    else:
        try:
            self.__pydantic_validated__ = False
            self.__pydantic_validator__.validate_python(
                self,
                strict=strict,
                from_attributes=True,
                context=context,
                self_instance=self,
            )
        except Exception as error:
            if raise_errors:
                raise error
            return False
        return True

model_update

model_update(
    obj: Any,
    *,
    update: dict[str, Any] | None = None,
    from_attributes: bool | None = None,
) -> None

Update the model with the given object and update dictionary.

Parameters:

Name Type Description Default
obj Any

The object to update the model with. It can be a dictionary or an object with attributes (if from_attributes is set to True). If it is a dictionary, the keys must match the model field names if extra fields are not allowed.

required
update dict[str, Any] | None

Values to add/modify within the model. Note that if assignment validation is not set to True, the integrity of the data is not validated when updating the model. Data should be trusted or pre-validated in this case. Defaults to None.

None
from_attributes bool | None

Whether to extract data from object attributes. Defaults to None.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

ValueError

If strict or context are set when validate_assignment is set to False.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_update(
    self,
    obj: Any,
    *,
    update: dict[str, Any] | None = None,
    from_attributes: bool | None = None,
) -> None:
    """Update the model with the given object and update dictionary.

    Args:
        obj: The object to update the model with. It can be a dictionary
            or an object with attributes (if `from_attributes` is set to
            ``True``). If it is a dictionary, the keys must match the model
            field names if extra fields are not allowed.
        update: Values to add/modify within the model. Note that if
            assignment validation is not set to ``True``, the integrity of
            the data is not validated when updating the model. Data should
            be trusted or pre-validated in this case. Defaults to ``None``.
        from_attributes: Whether to extract data from object attributes.
            Defaults to ``None``.

    Raises:
        ValidationError: If the object could not be validated.
        ValueError: If `strict` or `context` are set when
            `validate_assignment` is set to ``False``.
    """
    # Collect update
    update = (update or {}).copy()
    if from_attributes:
        for field_name in self.model_fields:
            if hasattr(obj, field_name):
                update.setdefault(field_name, getattr(obj, field_name))
    elif isinstance(obj, dict):
        update = {**obj, **update}

    # Process update
    for key, value in update.items():
        if key in self.model_fields:
            self.__dict__[key] = value
        else:
            if self.model_config.extra == 'allow':
                if self.__pydantic_extra__ is None:
                    self.__pydantic_extra__ = {}
                self.__pydantic_extra__[key] = value
            elif self.model_config.extra == 'ignore':
                self.__dict__[key] = value
            else:
                raise ValueError(
                    f"Extra field {key!r} is not permitted on the "
                    f"model {self.__class__.__qualname__!r}."
                )

    # Update fields set
    self.__pydantic_fields_set__.update(update.keys())

model_validate_many classmethod

model_validate_many(
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]

Validate the given object collection against the model.

Parameters:

Name Type Description Default
obj Any

The object collection to validate.

required
strict bool | None

Whether to enforce types strictly.

None
from_attributes bool | None

Whether to extract data from the object collection items attributes.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Sequence[Model]

A validated collection of model instances.

Raises:

Type Description
ValidationError

If the object collection could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_many(
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]:
    """Validate the given object collection against the model.

    Args:
        obj: The object collection to validate.
        strict: Whether to enforce types strictly.
        from_attributes: Whether to extract data from the object
            collection items attributes.
        context: Extra variables to pass to the validator.

    Returns:
        A validated collection of model instances.

    Raises:
        ValidationError: If the object collection could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.model_adapter.validate_python(  # type: ignore
        obj,
        strict=strict,
        from_attributes=from_attributes,
        context=context,
    )

model_validate_json_many classmethod

model_validate_json_many(
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]

Validate the given JSON data collection against the model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data collection to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Sequence[Model]

A validated collection of model instances.

Raises:

Type Description
ValueError

If json_data is not a JSON string.

ValidationError

If the object collection could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_json_many(
    cls: type[Model],
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]:
    """Validate the given JSON data collection against the model.

    Args:
        json_data: The JSON data collection to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        A validated collection of model instances.

    Raises:
        ValueError: If `json_data` is not a JSON string.
        ValidationError: If the object collection could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.model_adapter.validate_json(  # type: ignore
        json_data, strict=strict, context=context
    )

model_validate_strings_many classmethod

model_validate_strings_many(
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]

Validate the given string object collection against the model.

Parameters:

Name Type Description Default
obj Any

The string object collection to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Sequence[Model]

A validated collection of model instances.

Raises:

Type Description
ValidationError

If the object collection could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_strings_many(
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]:
    """Validate the given string object collection against the model.

    Args:
        obj: The string object collection to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        A validated collection of model instances.

    Raises:
        ValidationError: If the object collection could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.model_adapter.validate_strings(  # type: ignore
        obj, strict=strict, context=context
    )

model_construct classmethod

model_construct(
    root: _TRoot, _fields_set: set[str] | None = None
) -> Self

Create a new model using the provided root object and update fields set with the given set of fields.

Parameters:

Name Type Description Default
root _TRoot

The root object of the model.

required
_fields_set set[str] | None

The set of fields to be updated.

None

Returns:

Type Description
Self

The new model.

Raises:

Type Description
NotImplemented

If the model is not a subclass of RootModel.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_construct(  # type: ignore[override, unused-ignore]
    cls, root: _TRoot, _fields_set: set[str] | None = None
) -> Self:
    """Create a new model using the provided root object and update fields
    set with the given set of fields.

    Args:
        root: The root object of the model.
        _fields_set: The set of fields to be updated.

    Returns:
        The new model.

    Raises:
        NotImplemented: If the model is not a subclass of `RootModel`.
    """
    return super().model_construct(_fields_set, root=root)

model_dump

model_dump(
    *,
    mode: Literal["json", "python", "raw"] | str = "python",
    include: Any | None = None,
    exclude: Any | None = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> Any

This method is included just to get a more accurate return type for type checkers. It is included in this if TYPE_CHECKING: block since no override is actually necessary.

See the documentation of base model model_dump for more details about the arguments.

Generally, this method will have a return type of _TRoot, assuming that _TRoot is not a BaseModel subclass. If _TRoot is a BaseModel subclass, then the return type will likely be dict[str, Any], as model_dump calls are recursive. The return type could even be something different, in the case of a custom serializer. Thus, Any is used here to catch all of these cases.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_dump(  # type: ignore
    self,
    *,
    mode: Literal['json', 'python', 'raw'] | str = 'python',
    include: Any | None = None,
    exclude: Any | None = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> Any:
    """This method is included just to get a more accurate return type
    for type checkers. It is included in this `if TYPE_CHECKING:` block
    since no override is actually necessary.

    See the documentation of base model `model_dump` for more details
    about the arguments.

    Generally, this method will have a return type of `_TRoot`,
    assuming that `_TRoot` is not a `BaseModel` subclass. If `_TRoot`
    is a `BaseModel` subclass, then the return type will likely be
    `dict[str, Any]`, as `model_dump` calls are recursive. The return
    type could even be something different, in the case of a custom
    serializer. Thus, `Any` is used here to catch all of these cases.
    """
    ...

DiscriminatedModelMeta

DiscriminatedModelMeta(
    name: str,
    bases: tuple[type, ...],
    namespace: dict[str, Any],
    /,
    *args: Any,
    **kwargs: Any,
)

Bases: RootModelMeta

A metaclass for discriminated model classes.

Initialize a new discriminated model meta class.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(
    cls,
    name: str,
    bases: tuple[type, ...],
    namespace: dict[str, Any],
    /,
    *args: Any,
    **kwargs: Any,
) -> None:
    """Initialize a new discriminated model meta class."""
    super().__init__(
        name, bases, namespace, *args, **kwargs  # type: ignore
    )

    # Skip remaining initialization for the base class
    if isbaseclass_lenient(cls, 'DiscriminatedModel'):
        return

    # Collect the typevar values from the original bases found within
    # the class namespace and the provided bases.
    typevar_values = cls.collect_typevar_values(bases, namespace)

    # Retrieve discriminated model root type annotation
    if typevar_values is None:
        annotation = cls.model_fields['root'].annotation
    else:
        annotation = Union[typevar_values] \
            if len(typevar_values) > 1 \
            else typevar_values[0]  # type: ignore

    # Skip attribute initialization if generics still exist
    if isinstance(annotation, TypeVar):
        return

    # Set discriminated model root type annotation
    cls.model_fields['root'].annotation = cls.validate_root(annotation)

collect_config_wrappers

collect_config_wrappers(
    bases: tuple[type, ...], namespace: dict[str, Any]
) -> list[ConfigType]

Collect configuration wrappers from the given bases and namespace.

It collects the configuration wrappers from the given bases and namespace by extracting the configuration wrapper type from the original bases annotation if it is a generic subclass of the configurable class or metaclass, and from the configuration attribute if present in the class and bases namespace.

Parameters:

Name Type Description Default
bases tuple[type, ...]

The class bases.

required
namespace dict[str, Any]

The class namespace.

required

Returns:

Type Description
list[ConfigType]

A list of configuration wrapper classes found in the given bases

list[ConfigType]

and namespace.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
def collect_config_wrappers(
    cls, bases: tuple[type, ...], namespace: dict[str, Any], /,
) -> list[ConfigType]:
    """Collect configuration wrappers from the given bases and namespace.

    It collects the configuration wrappers from the given bases and
    namespace by extracting the configuration wrapper type from the
    original bases annotation if it is a generic subclass of the
    configurable class or metaclass, and from the configuration attribute
    if present in the class and bases namespace.

    Args:
        bases: The class bases.
        namespace: The class namespace.

    Returns:
        A list of configuration wrapper classes found in the given bases
        and namespace.
    """
    config_attr = getattr(cls, '__config_attr__', '__config__')
    config_wrappers: list[ConfigType] = []

    # The collection process is done in two steps to ensure that the
    # configuration attribute is extracted from the annotation first, and
    # then from the class and bases namespace.

    # Extract the configuration wrapper type from the annotation if it is a
    # generic subclass of the configurable class.
    meta_bases = get_meta_orig_bases(bases, namespace)
    for meta_base in meta_bases:
        origin = typing.get_origin(meta_base)
        if origin is None:
            continue
        if not isbaseclass_lenient(origin, 'Configurable'):
            continue
        args = typing.get_args(meta_base)
        if len(args) == 1:
            if isinstance(args[0], TypeVar):
                break
            if issubclass(args[0], ConfigWrapper):
                config_wrappers.append(args[0])
                break
        raise TypeError(
            f"Generic argument for the `Configurable` class must be a "
            f"subclass of the base configuration wrapper. Got: {args}."
        )

    # Extract the configuration wrapper type from the configuration
    # attribute if present in the class and bases namespace.
    meta_namespaces = get_meta_namespaces(bases, namespace)
    for meta_namespace in meta_namespaces:
        if config_attr not in meta_namespace:
            continue
        config_wrapper = meta_namespace[config_attr]
        if callable(config_wrapper):
            config_wrapper = config_wrapper()
        if isinstance(config_wrapper, ConfigWrapper):
            config_wrappers.append(config_wrapper.__class__)
            continue
        if isinstance(config_wrapper, dict):
            continue
        raise TypeError(
            f"Configuration attribute must be a dictionary or an "
            f"instance of the base configuration wrapper. Got: "
            f"{type(config_wrapper).__qualname__}."
        )

    return config_wrappers

collect_typevar_values

collect_typevar_values(
    bases: tuple[type, ...], namespace: dict[str, Any]
) -> tuple[type[Any], ...] | None

Collect the root typevar values.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def collect_typevar_values(
    cls, bases: tuple[type, ...], namespace: dict[str, Any], /,
) -> tuple[type[Any], ...] | None:
    """Collect the root typevar values."""
    generic_attr = '__pydantic_generic_metadata__'

    meta_bases = get_meta_orig_bases(bases, namespace)
    for meta_base in meta_bases:
        generic = getattr(meta_base, generic_attr, {})
        origin = generic.get('origin', meta_base)
        if origin is None:
            continue
        if not isbaseclass_lenient(origin, 'DiscriminatedModel'):
            continue
        args = generic.get('args', ())
        if any(isinstance(arg, TypeVar) for arg in args):
            break
        return args  # type: ignore

    return None

get_root_members

get_root_members() -> tuple[ModelType, ...]

Get the base and variant classes of the discriminated model.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def get_root_members(cls) -> tuple[ModelType, ...]:
    """Get the base and variant classes of the discriminated model."""
    annotation = cls.model_fields['root'].annotation
    members = typing.get_args(annotation) or (annotation,)
    return tuple([
        member for member in members
        if isinstance(member, type) and issubclass(member, BaseModel)
    ])

get_root_base

get_root_base() -> ModelType

Get the base class of the discriminated model.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def get_root_base(cls) -> ModelType:
    """Get the base class of the discriminated model."""
    members = cls.get_root_members()
    if len(members) == 0:
        raise TypeError(
            f"Root base model not found for the `DiscriminatedModel` "
            f"class. Got: {members}."
        )
    return members[0]

get_root_variants

get_root_variants() -> tuple[ModelType, ...]

Get the variant classes of the discriminated model.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def get_root_variants(cls) -> tuple[ModelType, ...]:
    """Get the variant classes of the discriminated model."""
    members = cls.get_root_members()
    if len(members) == 0:
        raise TypeError(
            f"Root base model not found for the `DiscriminatedModel` "
            f"class. Got: {members}."
        )
    return members[1:]

update_root_members

update_root_members(
    *,
    base: type[Any] | None = None,
    variants: Sequence[type[Any]] | None = None,
) -> tuple[ModelType, ...]

Update the discriminator with the given models.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def update_root_members(
    cls,
    *,
    base: type[Any] | None = None,
    variants: Sequence[type[Any]] | None = None,
) -> tuple[ModelType, ...]:
    """Update the discriminator with the given models."""
    if base is None:
        base = cls.get_root_base()  # type: ignore
        assert base is not None
    if variants is None:
        variants = ()

    if not all(issubclass(variant, base) for variant in variants):
        raise TypeError(
            f"Model variants must be subclasses of the root base "
            f"model. Got: {variants}."
        )
    if any(variant is base for variant in variants):
        raise TypeError(
            f"Cannot provide the root base model as a variant. "
            f"Got: {variants}."
        )

    models = (base, *variants)
    cls.model_fields['root'].annotation = Union[models]  # type: ignore

    return models

update_root_metadata

update_root_metadata(*metadata: Any) -> tuple[Any, ...]

Update root type metadata.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def update_root_metadata(cls, *metadata: Any) -> tuple[Any, ...]:
    """Update root type metadata."""
    annotation = cls.model_fields['root'].annotation
    annotation_metadata = tuple(
        Field(..., discriminator=meta)
        for meta in metadata
        if isinstance(meta, (str, Discriminator)) or meta
    )
    cls.model_fields['root'] = FieldInfo.from_field_info(
        cls.model_fields['root'],
        annotation=Annotated[
            annotation, *annotation_metadata  # type: ignore
        ],
    )

    return annotation_metadata

validate_root

validate_root(annotation: Any) -> ModelType

Validate the root type annotation of the discriminated model.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def validate_root(cls, annotation: Any) -> ModelType:
    """Validate the root type annotation of the discriminated model."""
    # Parse the root type annotation
    origin = typing.get_origin(annotation)
    if origin in (Union, UnionType):
        args = typing.get_args(annotation)
    else:
        args = (annotation,)

    # Validate the root type annotation
    if not is_model(args[0]) and not is_resource(args[0]):
        raise TypeError(
            f"The root base type for the `DiscriminatedModel` class "
            f"must be a subclass of the `BaseModel` or `BaseResource` "
            f"class. Got: {args[0]}."
        )
    if not all(issubclass(arg, args[0]) for arg in args[1:]):
        raise TypeError(
            f"The root variant types for the `DiscriminatedModel` "
            f"class must be subclasses of the root base type. "
            f"Got: {args[1:]}."
        )

    return annotation  # type: ignore

DiscriminatedModel

DiscriminatedModel(root: _TRoot = Undefined, **data: Any)

Bases: RootModel[_TBase], Generic[_TBase, *_TSubs]

A discriminated model class.

Initialize a root model instance.

It initializes a model instance by parsing and validating input data from the root argument or data keyword arguments.

Parameters:

Name Type Description Default
root _TRoot

The root object of the model.

Undefined
**data Any

The input data to initialize the model instance.

{}

Raises:

Type Description
ValidationError

If the object could not be validated.

Note

The argument self is explicitly positional-only to allow self as a field name and data keyword argument.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, root: _TRoot = Undefined, **data: Any) -> None:
    """Initialize a root model instance.

    It initializes a model instance by parsing and validating input data
    from the `root` argument or `data` keyword arguments.

    Args:
        root: The root object of the model.
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    if data:
        if root is not Undefined:
            raise ValueError(
                f"Root model `__init__` accepts either a single "
                f"positional argument or arbitrary keyword arguments. "
                f"Got both: root={root!r}, data={data!r}"
            )
        root = data  # type: ignore

    self.__pydantic_validator__.validate_python(root, self_instance=self)

model_extra property

model_extra: dict[str, Any] | None

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

model_fields_set: set[str]

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

model_construct classmethod

model_construct(
    root: _TRoot, _fields_set: set[str] | None = None
) -> Self

Create a new model using the provided root object and update fields set with the given set of fields.

Parameters:

Name Type Description Default
root _TRoot

The root object of the model.

required
_fields_set set[str] | None

The set of fields to be updated.

None

Returns:

Type Description
Self

The new model.

Raises:

Type Description
NotImplemented

If the model is not a subclass of RootModel.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_construct(  # type: ignore[override, unused-ignore]
    cls, root: _TRoot, _fields_set: set[str] | None = None
) -> Self:
    """Create a new model using the provided root object and update fields
    set with the given set of fields.

    Args:
        root: The root object of the model.
        _fields_set: The set of fields to be updated.

    Returns:
        The new model.

    Raises:
        NotImplemented: If the model is not a subclass of `RootModel`.
    """
    return super().model_construct(_fields_set, root=root)

model_copy

model_copy(
    *,
    update: dict[str, Any] | None = None,
    deep: bool = False,
) -> Model

Returns a copy of the model.

Parameters:

Name Type Description Default
update dict[str, Any] | None

Values to add/modify within the new model. Note that if assignment validation is not set to True, the integrity of the data is not validated when creating the new model. Data should be trusted or pre-validated in this case.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Model

A new copy of the model instance with the updated values.

Raises:

Type Description
ValidationError

If the object could not be validated.

ValueError

If strict or context are set when validate_assignment is set to False.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_copy(  # type: ignore[override, unused-ignore]
    self: Model,
    *,
    update: dict[str, Any] | None = None,
    deep: bool = False,
) -> Model:
    """Returns a copy of the model.

    Args:
        update: Values to add/modify within the new model. Note that if
            assignment validation is not set to ``True``, the integrity of
            the data is not validated when creating the new model. Data
            should be trusted or pre-validated in this case.
        deep: Set to ``True`` to make a deep copy of the model.

    Returns:
        A new copy of the model instance with the updated values.

    Raises:
        ValidationError: If the object could not be validated.
        ValueError: If `strict` or `context` are set when
            `validate_assignment` is set to ``False``.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        copied.model_update(update, from_attributes=False)
    return copied

model_dump

model_dump(
    *,
    mode: Literal["json", "python", "raw"] | str = "python",
    include: Any | None = None,
    exclude: Any | None = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> Any

This method is included just to get a more accurate return type for type checkers. It is included in this if TYPE_CHECKING: block since no override is actually necessary.

See the documentation of base model model_dump for more details about the arguments.

Generally, this method will have a return type of _TRoot, assuming that _TRoot is not a BaseModel subclass. If _TRoot is a BaseModel subclass, then the return type will likely be dict[str, Any], as model_dump calls are recursive. The return type could even be something different, in the case of a custom serializer. Thus, Any is used here to catch all of these cases.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_dump(  # type: ignore
    self,
    *,
    mode: Literal['json', 'python', 'raw'] | str = 'python',
    include: Any | None = None,
    exclude: Any | None = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> Any:
    """This method is included just to get a more accurate return type
    for type checkers. It is included in this `if TYPE_CHECKING:` block
    since no override is actually necessary.

    See the documentation of base model `model_dump` for more details
    about the arguments.

    Generally, this method will have a return type of `_TRoot`,
    assuming that `_TRoot` is not a `BaseModel` subclass. If `_TRoot`
    is a `BaseModel` subclass, then the return type will likely be
    `dict[str, Any]`, as `model_dump` calls are recursive. The return
    type could even be something different, in the case of a custom
    serializer. Thus, `Any` is used here to catch all of these cases.
    """
    ...

model_dump_json

model_dump_json(
    *,
    indent: int | None = None,
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> str

Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
include IncEx

Field(s) to include in the JSON output.

None
exclude IncEx

Field(s) to exclude from the JSON output.

None
by_alias bool

Whether to serialize using field aliases.

False
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool

Whether to log warnings when invalid fields are encountered.

True

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> str:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump_json

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: Whether to log warnings when invalid fields are encountered.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        include=include,
        exclude=exclude,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        round_trip=round_trip,
        warnings=warnings,
    ).decode()

model_json_schema classmethod

model_json_schema(
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[
        GenerateJsonSchema
    ] = GenerateJsonSchema,
    mode: JsonSchemaMode = "validation",
    source: JsonSchemaSource = "model",
) -> dict[str, Any]

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use field aliases when generating the schema, i.e. if True, fields will be serialized according to their alias, otherwise according to their attribute name. Defaults to True.

True
ref_template str

The template format string used when generating reference names. Defaults to DEFAULT_REF_TEMPLATE.

DEFAULT_REF_TEMPLATE
schema_generator type[GenerateJsonSchema]

The class to use for generating the JSON Schema.

GenerateJsonSchema
mode JsonSchemaMode

The mode to use for generating the JSON Schema. It can be either validation or serialization where respectively the schema is generated for validating data or serializing data. Defaults to validation.

'validation'
source JsonSchemaSource

The source type to use for generating the resources JSON schema. It can be either key , model, or both where the latter accepts, when applicable, integer and string values for key identifiers in addition to the standard model schema generation. Defaults to model.

'model'

Returns:

Type Description
dict[str, Any]

The generated JSON schema of the model class.

Note

The schema generator class can be overridden to customize the logic used to generate the JSON schema. This can be done by subclassing the GenerateJsonSchema class and passing the subclass as the schema_generator argument.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_json_schema(  # type: ignore[override, unused-ignore]
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    source: JsonSchemaSource = 'model',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use field aliases when generating the schema,
            i.e. if ``True``, fields will be serialized according to their
            alias, otherwise according to their attribute name.
            Defaults to ``True``.
        ref_template: The template format string used when generating
            reference names. Defaults to ``DEFAULT_REF_TEMPLATE``.
        schema_generator: The class to use for generating the JSON Schema.
        mode: The mode to use for generating the JSON Schema. It can be
            either ``validation`` or ``serialization`` where respectively
            the schema is generated for validating data or serializing
            data. Defaults to ``validation``.
        source: The source type to use for generating the resources JSON
            schema. It can be either ``key`` , ``model``, or ``both`` where
            the latter accepts, when applicable, integer and string values
            for key identifiers in addition to the standard model schema
            generation. Defaults to ``model``.

    Returns:
        The generated JSON schema of the model class.

    Note:
        The schema generator class can be overridden to customize the
        logic used to generate the JSON schema. This can be done by
        subclassing the `GenerateJsonSchema` class and passing the subclass
        as the `schema_generator` argument.
    """
    schema_generator_instance = schema_generator(
        by_alias=by_alias, ref_template=ref_template
    )
    if isinstance(cls.__pydantic_validator__, _mock_val_ser.MockValSer):
        cls.__pydantic_validator__.rebuild()
    return schema_generator_instance.generate(
        cls.__pydantic_core_schema__, mode=mode, source=source
    )

model_parametrized_name classmethod

model_parametrized_name(
    params: tuple[type[Any], ...],
) -> str

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, typing.Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init

model_post_init(__context: Any) -> None

Post-initialization method for the model class.

Override this method to perform additional initialization after the __init__ and model_construct methods have been called. This is useful in scenarios where it is necessary to perform additional initialization steps after the model has been fully initialized.

Parameters:

Name Type Description Default
__context Any

The context object passed to the model instance.

required
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_post_init(self, __context: Any) -> None:
    """Post-initialization method for the model class.

    Override this method to perform additional initialization after the
    `__init__` and `model_construct` methods have been called. This is
    useful in scenarios where it is necessary to perform additional
    initialization steps after the model has been fully initialized.

    Args:
        __context: The context object passed to the model instance.
    """
    ...

model_rebuild classmethod

model_rebuild(
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: dict[str, Any] | None = None,
) -> bool | None

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema. Defaults to False.

False
raise_errors bool

Whether to raise errors or fail silently. Defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace. Defaults to 2.

2
_types_namespace dict[str, Any] | None

The types namespace. Defaults to None.

None

Raises:

Type Description
PlateformeError

If an error occurred while rebuilding the model adapter and raise_errors is set to True.

PydanticUndefinedAnnotation

If PydanticUndefinedAnnotation occurs in__get_pydantic_core_schema__ and raise_errors is set to True.

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding

bool | None

was not required. If rebuilding was required, returns True if

bool | None

rebuilding was successful, otherwise False if an error

bool | None

occurred and raise_errors is set to False.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_rebuild(  # type: ignore[override, unused-ignore]
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: dict[str, Any] | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a `ForwardRef`
    which could not be resolved during the initial attempt to build the
    schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema.
            Defaults to ``False``.
        raise_errors: Whether to raise errors or fail silently.
            Defaults to ``True``.
        _parent_namespace_depth: The depth level of the parent namespace.
            Defaults to 2.
        _types_namespace: The types namespace. Defaults to ``None``.

    Raises:
        PlateformeError: If an error occurred while rebuilding the model
            adapter and `raise_errors` is set to ``True``.
        PydanticUndefinedAnnotation: If `PydanticUndefinedAnnotation`
            occurs in`__get_pydantic_core_schema__` and `raise_errors` is
            set to ``True``.

    Returns:
        Returns ``None`` if the schema is already "complete" and rebuilding
        was not required. If rebuilding was required, returns ``True`` if
        rebuilding was successful, otherwise ``False`` if an error
        occurred and `raise_errors` is set to ``False``.
    """
    build_status: bool | None = None

    # Rebuild model
    build_status = super().model_rebuild(
        force=build_status or force,
        raise_errors=raise_errors,
        _parent_namespace_depth=_parent_namespace_depth,
        _types_namespace=_types_namespace,
    )

    # Rebuild model adapter
    if build_status:
        try:
            adapter = TypeAdapterList(cls)
            setattr(cls, '__pydantic_adapter__', adapter)
        except Exception as error:
            if not raise_errors:
                return False
            raise PlateformeError(
                f"Failed to rebuild model adapter for {cls.__name__!r}.",
                code='model-build-failed',
            )

    if build_status is not False:
        cls.model_config.pop('defer_build')

    return build_status

model_validate classmethod

model_validate(
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate the given object against the model.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
from_attributes bool | None

Whether to extract data from the object attributes.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

A validated model instance.

Raises:

Type Description
ValidationError

If the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate(  # type: ignore[override, unused-ignore]
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate the given object against the model.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        from_attributes: Whether to extract data from the object
            attributes.
        context: Extra variables to pass to the validator.

    Returns:
        A validated model instance.

    Raises:
        ValidationError: If the object could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.__pydantic_validator__.validate_python(  # type: ignore
        obj,
        strict=strict,
        from_attributes=from_attributes,
        context=context,
    )

model_validate_json classmethod

model_validate_json(
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate the given JSON data against the model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

A validated model instance.

Raises:

Type Description
ValueError

If json_data is not a JSON string.

ValidationError

If the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_json(  # type: ignore[override, unused-ignore]
    cls: type[Model],
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate the given JSON data against the model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        A validated model instance.

    Raises:
        ValueError: If `json_data` is not a JSON string.
        ValidationError: If the object could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.__pydantic_validator__.validate_json(  # type: ignore
        json_data, strict=strict, context=context
    )

model_validate_strings classmethod

model_validate_strings(
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate the given string object against the model.

Parameters:

Name Type Description Default
obj Any

The string object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

A validated model instance.

Raises:

Type Description
ValidationError

If the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_strings(  # type: ignore[override, unused-ignore]
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate the given string object against the model.

    Args:
        obj: The string object to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        A validated model instance.

    Raises:
        ValidationError: If the object could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.__pydantic_validator__.validate_strings(  # type: ignore
        obj, strict=strict, context=context
    )

copy

copy(
    *,
    include: AbstractSetIntStr
    | MappingIntStrAny
    | None = None,
    exclude: AbstractSetIntStr
    | MappingIntStrAny
    | None = None,
    update: Dict[str, Any] | None = None,
    deep: bool = False,
) -> Model

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Model

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self: Model,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: typing.Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Model:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```py
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_adapter

model_adapter() -> TypeAdapterList[BaseModel]

Get the model type adapter.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classproperty
def model_adapter(cls) -> TypeAdapterList['BaseModel']:
    """Get the model type adapter."""
    if not hasattr(cls, '__pydantic_adapter__'):
        raise AttributeError(
            "The model type adapter is not defined. This may be due to "
            "the model not being fully built or an error occurred during "
            "model construction."
        )
    return cls.__pydantic_adapter__

model_revalidate

model_revalidate(
    *,
    force: bool = False,
    raise_errors: bool = True,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> bool | None

Revalidate the model instance.

It revalidates the model instance in place, enforcing the types strictly if specified. If the model instance has already been validated, it will not be revalidated unless the force argument is set to True.

Parameters:

Name Type Description Default
force bool

Whether to force the revalidation of the model instance. Defaults to False.

False
raise_errors bool

Whether to raise errors or fail silently. Defaults to True.

True
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Raises:

Type Description
ValidationError

If the model instance could not be validated and raise_errors is set to True.

Returns:

Type Description
bool | None

Returns None if the model instance is already "validated" and

bool | None

revalidation was not required. If validation was required, returns

bool | None

True if validation was successful, otherwise False if an

bool | None

error occurred and raise_errors is set to False.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_revalidate(
    self,
    *,
    force: bool = False,
    raise_errors: bool = True,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> bool | None:
    """Revalidate the model instance.

    It revalidates the model instance in place, enforcing the types
    strictly if specified. If the model instance has already been
    validated, it will not be revalidated unless the `force` argument is
    set to ``True``.

    Args:
        force: Whether to force the revalidation of the model instance.
            Defaults to ``False``.
        raise_errors: Whether to raise errors or fail silently.
            Defaults to ``True``.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Raises:
        ValidationError: If the model instance could not be validated and
            `raise_errors` is set to ``True``.

    Returns:
        Returns ``None`` if the model instance is already "validated" and
        revalidation was not required. If validation was required, returns
        ``True`` if validation was successful, otherwise ``False`` if an
        error occurred and `raise_errors` is set to ``False``.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    if not force and self.__pydantic_validated__:
        return None
    else:
        try:
            self.__pydantic_validated__ = False
            self.__pydantic_validator__.validate_python(
                self,
                strict=strict,
                from_attributes=True,
                context=context,
                self_instance=self,
            )
        except Exception as error:
            if raise_errors:
                raise error
            return False
        return True

model_update

model_update(
    obj: Any,
    *,
    update: dict[str, Any] | None = None,
    from_attributes: bool | None = None,
) -> None

Update the model with the given object and update dictionary.

Parameters:

Name Type Description Default
obj Any

The object to update the model with. It can be a dictionary or an object with attributes (if from_attributes is set to True). If it is a dictionary, the keys must match the model field names if extra fields are not allowed.

required
update dict[str, Any] | None

Values to add/modify within the model. Note that if assignment validation is not set to True, the integrity of the data is not validated when updating the model. Data should be trusted or pre-validated in this case. Defaults to None.

None
from_attributes bool | None

Whether to extract data from object attributes. Defaults to None.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

ValueError

If strict or context are set when validate_assignment is set to False.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def model_update(
    self,
    obj: Any,
    *,
    update: dict[str, Any] | None = None,
    from_attributes: bool | None = None,
) -> None:
    """Update the model with the given object and update dictionary.

    Args:
        obj: The object to update the model with. It can be a dictionary
            or an object with attributes (if `from_attributes` is set to
            ``True``). If it is a dictionary, the keys must match the model
            field names if extra fields are not allowed.
        update: Values to add/modify within the model. Note that if
            assignment validation is not set to ``True``, the integrity of
            the data is not validated when updating the model. Data should
            be trusted or pre-validated in this case. Defaults to ``None``.
        from_attributes: Whether to extract data from object attributes.
            Defaults to ``None``.

    Raises:
        ValidationError: If the object could not be validated.
        ValueError: If `strict` or `context` are set when
            `validate_assignment` is set to ``False``.
    """
    # Collect update
    update = (update or {}).copy()
    if from_attributes:
        for field_name in self.model_fields:
            if hasattr(obj, field_name):
                update.setdefault(field_name, getattr(obj, field_name))
    elif isinstance(obj, dict):
        update = {**obj, **update}

    # Process update
    for key, value in update.items():
        if key in self.model_fields:
            self.__dict__[key] = value
        else:
            if self.model_config.extra == 'allow':
                if self.__pydantic_extra__ is None:
                    self.__pydantic_extra__ = {}
                self.__pydantic_extra__[key] = value
            elif self.model_config.extra == 'ignore':
                self.__dict__[key] = value
            else:
                raise ValueError(
                    f"Extra field {key!r} is not permitted on the "
                    f"model {self.__class__.__qualname__!r}."
                )

    # Update fields set
    self.__pydantic_fields_set__.update(update.keys())

model_validate_many classmethod

model_validate_many(
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]

Validate the given object collection against the model.

Parameters:

Name Type Description Default
obj Any

The object collection to validate.

required
strict bool | None

Whether to enforce types strictly.

None
from_attributes bool | None

Whether to extract data from the object collection items attributes.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Sequence[Model]

A validated collection of model instances.

Raises:

Type Description
ValidationError

If the object collection could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_many(
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]:
    """Validate the given object collection against the model.

    Args:
        obj: The object collection to validate.
        strict: Whether to enforce types strictly.
        from_attributes: Whether to extract data from the object
            collection items attributes.
        context: Extra variables to pass to the validator.

    Returns:
        A validated collection of model instances.

    Raises:
        ValidationError: If the object collection could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.model_adapter.validate_python(  # type: ignore
        obj,
        strict=strict,
        from_attributes=from_attributes,
        context=context,
    )

model_validate_json_many classmethod

model_validate_json_many(
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]

Validate the given JSON data collection against the model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data collection to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Sequence[Model]

A validated collection of model instances.

Raises:

Type Description
ValueError

If json_data is not a JSON string.

ValidationError

If the object collection could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_json_many(
    cls: type[Model],
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]:
    """Validate the given JSON data collection against the model.

    Args:
        json_data: The JSON data collection to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        A validated collection of model instances.

    Raises:
        ValueError: If `json_data` is not a JSON string.
        ValidationError: If the object collection could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.model_adapter.validate_json(  # type: ignore
        json_data, strict=strict, context=context
    )

model_validate_strings_many classmethod

model_validate_strings_many(
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]

Validate the given string object collection against the model.

Parameters:

Name Type Description Default
obj Any

The string object collection to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Sequence[Model]

A validated collection of model instances.

Raises:

Type Description
ValidationError

If the object collection could not be validated.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
@classmethod
def model_validate_strings_many(
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Sequence[Model]:
    """Validate the given string object collection against the model.

    Args:
        obj: The string object collection to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        A validated collection of model instances.

    Raises:
        ValidationError: If the object collection could not be validated.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    return cls.model_adapter.validate_strings(  # type: ignore
        obj, strict=strict, context=context
    )

ModelFieldLookup

Bases: TypedDict

A model field lookup configuration.

include instance-attribute

include: dict[str, IncExPredicate] | None

The filters for including specific fields as a dictionary with the field attribute names as keys and the values to match. Specified keys can use the . notation to access nested attributes. Additionally, the lookup attributes can be callables without arguments. Defaults to None.

exclude instance-attribute

exclude: dict[str, IncExPredicate] | None

The filters for excluding specific fields as a dictionary with the field attribute names as keys and the values to not match. Specified keys can use the . notation to access nested attributes. Additionally, the lookup attributes can be callable without arguments. Defaults to None.

partial instance-attribute

partial: bool | None

Whether to mark the field annotations as optional. Defaults to None.

default instance-attribute

default: dict[str, Any] | None

The default to apply and set within the field information. Defaults to None.

update instance-attribute

update: dict[str, Any] | None

The update to apply and set within the field information. Defaults to None.

override instance-attribute

override: ModelFieldLookup | None

The field lookup configuration to override the current configuration. This can be used to narrow down the field lookup configuration to specific fields. Multiple levels of nested configurations can be provided and will be resolved recursively. Defaults to None.

NoInitField

NoInitField(*, init: Literal[False] = False) -> Any

Only for typing purposes. Used as default value of the attribute __pydantic_fields_set__, __pydantic_extra__, __pydantic_private__, so they could be ignored when synthesizing the __init__ signature.

See Pydantic base model metaclass signature for more information.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def NoInitField(*, init: Literal[False] = False) -> Any:
    """Only for typing purposes. Used as default value of the attribute
    `__pydantic_fields_set__`, `__pydantic_extra__`, `__pydantic_private__`, so
    they could be ignored when synthesizing the `__init__` signature.

    See Pydantic base model metaclass signature for more information.
    """

create_model

create_model(
    __model_name: str,
    *,
    __config__: ModelConfig | None = None,
    __doc__: str | None = None,
    __base__: None = None,
    __module__: str = __name__,
    __validators__: dict[str, ClassMethodType]
    | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    **field_definitions: tuple[
        type[Any], Any | ModelFieldInfo
    ],
) -> ModelType
create_model(
    __model_name: str,
    *,
    __config__: ModelConfig | None = None,
    __doc__: str | None = None,
    __base__: type[Model] | tuple[type[Model], ...],
    __module__: str = __name__,
    __validators__: dict[str, ClassMethodType]
    | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    **field_definitions: tuple[
        type[Any], Any | ModelFieldInfo
    ],
) -> type[Model]
create_model(
    __model_name: str,
    *,
    __config__: ModelConfig | None = None,
    __doc__: str | None = None,
    __base__: type[Model]
    | tuple[type[Model], ...]
    | None = None,
    __module__: str | None = None,
    __validators__: dict[str, ClassMethodType]
    | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    **field_definitions: tuple[
        type[Any], Any | ModelFieldInfo
    ],
) -> type[Model]

Dynamically creates and returns a new model class.

It is used to dynamically create a subclass of the BaseModel class.

Parameters:

Name Type Description Default
__model_name str

The name of the newly created model.

required
__config__ ModelConfig | None

The configuration of the new model.

None
__doc__ str | None

The docstring of the new model.

None
__base__ type[Model] | tuple[type[Model], ...] | None

The base class or classes for the new model.

None
__module__ str | None

The name of the module that the model belongs to. If None, the value is retrieved from sys._getframe(1).

None
__validators__ dict[str, ClassMethodType] | None

A dictionary of class methods that validate fields.

None
__cls_kwargs__ dict[str, Any] | None

A dictionary of keyword arguments for class creation, such as metaclass.

None
**field_definitions tuple[type[Any], Any | ModelFieldInfo]

Attributes of the new model. They should be passed in the format: <name>=(<type>, <default value>) or <name>=(<type>, <FieldInfo>).

{}

Returns:

Type Description
type[Model]

The new BaseModel class.

Raises:

Type Description
ValueError

If __base__ and __config__ are both passed.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def create_model(
    __model_name: str,
    *,
    __config__: ModelConfig | None = None,
    __doc__: str | None = None,
    __base__: type[Model] | tuple[type[Model], ...] | None = None,
    __module__: str | None = None,
    __validators__: dict[str, ClassMethodType] | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    **field_definitions: tuple[type[Any], Any | ModelFieldInfo],
) -> type[Model]:
    """Dynamically creates and returns a new model class.

    It is used to dynamically create a subclass of the `BaseModel` class.

    Args:
        __model_name: The name of the newly created model.
        __config__: The configuration of the new model.
        __doc__: The docstring of the new model.
        __base__: The base class or classes for the new model.
        __module__: The name of the module that the model belongs to.
            If ``None``, the value is retrieved from ``sys._getframe(1)``.
        __validators__: A dictionary of class methods that validate fields.
        __cls_kwargs__: A dictionary of keyword arguments for class creation,
            such as ``metaclass``.
        **field_definitions: Attributes of the new model. They should be passed
            in the format: ``<name>=(<type>, <default value>)`` or
            ``<name>=(<type>, <FieldInfo>)``.

    Returns:
        The new `BaseModel` class.

    Raises:
        ValueError: If `__base__` and `__config__` are both passed.
    """
    # Create factory model class and update configuration
    if __base__ is None:
        model_config = __config__ or ModelConfig()
        class FactoryModel(BaseModel):
            __config__ = model_config
        __config__ = None
        __base__ = typing.cast(type[Model], FactoryModel)

    # Validate configuration
    elif __config__ is not None:
        raise ValueError(
            "The `__config__` and `__base__` arguments cannot be used "
            "together when creating a model."
        )

    # Validate model name
    model_qualname = __model_name
    model_name = __model_name.split('.')[-1]

    # Create model using Pydantic factory with updated configuration
    model = _create_model(  # type: ignore
        model_name,
        __config__=__config__,
        __doc__=__doc__,
        __base__=__base__,
        __module__=__module__,  # type: ignore[arg-type]
        __validators__=__validators__,
        __cls_kwargs__=__cls_kwargs__,
        __slots__=None,
        **field_definitions,
    )

    setattr(model, '__qualname__', model_qualname)

    return model

create_root_model

create_root_model(
    __model_name: str,
    *,
    __config__: ModelConfig | None = None,
    __doc__: str | None = None,
    __module__: str | None = None,
    __validators__: dict[str, ClassMethodType]
    | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    root: tuple[type[_TRoot], Any | ModelFieldInfo],
) -> type[RootModel[_TRoot]]

Dynamically creates and returns a new model class.

It is used to dynamically create a subclass of the BaseModel class.

Parameters:

Name Type Description Default
__model_name str

The name of the newly created model.

required
__config__ ModelConfig | None

The configuration of the new model.

None
__doc__ str | None

The docstring of the new model.

None
__module__ str | None

The name of the module that the model belongs to. If None, the value is retrieved from sys._getframe(1).

None
__validators__ dict[str, ClassMethodType] | None

A dictionary of class methods that validate fields.

None
__cls_kwargs__ dict[str, Any] | None

A dictionary of keyword arguments for class creation, such as metaclass.

None
root tuple[type[_TRoot], Any | ModelFieldInfo]

Root attributes of the new model. It should be passed in the format: <name>=(<type>, <default value>) or <name>=(<type>, <FieldInfo>).

required

Returns:

Type Description
type[RootModel[_TRoot]]

The new RootModel class.

Raises:

Type Description
ValueError

If __base__ and __config__ are both passed.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def create_root_model(
    __model_name: str,
    *,
    __config__: ModelConfig | None = None,
    __doc__: str | None = None,
    __module__: str | None = None,
    __validators__: dict[str, ClassMethodType] | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    root: tuple[type[_TRoot], Any | ModelFieldInfo]
) -> type[RootModel[_TRoot]]:
    """Dynamically creates and returns a new model class.

    It is used to dynamically create a subclass of the `BaseModel` class.

    Args:
        __model_name: The name of the newly created model.
        __config__: The configuration of the new model.
        __doc__: The docstring of the new model.
        __module__: The name of the module that the model belongs to.
            If ``None``, the value is retrieved from ``sys._getframe(1)``.
        __validators__: A dictionary of class methods that validate fields.
        __cls_kwargs__: A dictionary of keyword arguments for class creation,
            such as ``metaclass``.
        root: Root attributes of the new model. It should be passed in
            the format: ``<name>=(<type>, <default value>)`` or
            ``<name>=(<type>, <FieldInfo>)``.

    Returns:
        The new `RootModel` class.

    Raises:
        ValueError: If `__base__` and `__config__` are both passed.
    """
    # Create the factory model class and update configuration
    model_config = __config__ or ModelConfig()
    class FactoryModel(RootModel[_TRoot]):
        __config__ = model_config
    __base__ = typing.cast(type[RootModel[_TRoot]], FactoryModel)

    # Create model using Pydantic factory with updated configuration
    return _create_model(
        __model_name,
        __doc__=__doc__,
        __base__=__base__,
        __module__=__module__,  # type: ignore[arg-type]
        __validators__=__validators__,
        __cls_kwargs__=__cls_kwargs__,
        __slots__=None,
        root=root,
    )

create_discriminated_model

create_discriminated_model(
    __model_name: str,
    *,
    __owner__: object | int | None = None,
    __config__: ModelConfig | None = None,
    __doc__: str | None = None,
    __module__: str | None = None,
    __validators__: dict[str, ClassMethodType]
    | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    discriminator: str | Discriminator | None = None,
    root: tuple[type[_TBase], Any | ModelFieldInfo],
) -> type[DiscriminatedModel[_TBase]]
create_discriminated_model(
    __model_name: str,
    *,
    __owner__: object | int | None = None,
    __config__: ModelConfig | None = None,
    __doc__: str | None = None,
    __module__: str | None = None,
    __validators__: dict[str, ClassMethodType]
    | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    discriminator: str | Discriminator | None = None,
    root: tuple[
        tuple[type[_TBase], ...], Any | ModelFieldInfo
    ],
) -> type[DiscriminatedModel[*tuple[_TBase, ...],]]
create_discriminated_model(
    __model_name: str,
    *,
    __owner__: object | int | None = None,
    __config__: ModelConfig | None = None,
    __doc__: str | None = None,
    __module__: str | None = None,
    __validators__: dict[str, ClassMethodType]
    | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    discriminator: str | Discriminator | None = None,
    root: tuple[
        type[_TBase] | tuple[type[_TBase], ...],
        Any | ModelFieldInfo,
    ],
) -> type[DiscriminatedModel[*tuple[_TBase, ...],]]

Dynamically creates and returns a new model class.

It is used to dynamically create a subclass of the BaseModel class.

Parameters:

Name Type Description Default
__model_name str

The name of the newly created model.

required
__owner__ object | int | None

The owner object or identifier to use as the registrant of the new model. If an object is provided, the object's identifier is used. If an integer is provided, the integer is used. Defaults to None.

None
__config__ ModelConfig | None

The configuration of the new model.

None
__doc__ str | None

The docstring of the new model.

None
__module__ str | None

The name of the module that the model belongs to. If None, the value is retrieved from sys._getframe(1).

None
__validators__ dict[str, ClassMethodType] | None

A dictionary of class methods that validate fields.

None
__cls_kwargs__ dict[str, Any] | None

A dictionary of keyword arguments for class creation, such as metaclass.

None
discriminator str | Discriminator | None

The discriminator either as a string or an object use for the validation of the discriminated root type.

None
root tuple[type[_TBase] | tuple[type[_TBase], ...], Any | ModelFieldInfo]

Root attributes of the new model. It should be passed in the format: <name>=(<type>, <default value>) or <name>=(<type>, <FieldInfo>).

required

Returns:

Type Description
type[DiscriminatedModel[*tuple[_TBase, ...],]]

The new DiscriminatedModel class.

Raises:

Type Description
ValueError

If __base__ and __config__ are both passed.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def create_discriminated_model(
    __model_name: str,
    *,
    __owner__: object | int | None = None,
    __config__: ModelConfig | None = None,
    __doc__: str | None = None,
    __module__: str | None = None,
    __validators__: dict[str, ClassMethodType] | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    discriminator: str | Discriminator | None = None,
    root: tuple[type[_TBase] | tuple[type[_TBase], ...], Any | ModelFieldInfo]
) -> type[DiscriminatedModel[*tuple[_TBase, ...]]]:
    """Dynamically creates and returns a new model class.

    It is used to dynamically create a subclass of the `BaseModel` class.

    Args:
        __model_name: The name of the newly created model.
        __owner__: The owner object or identifier to use as the registrant of
            the new model. If an object is provided, the object's identifier
            is used. If an integer is provided, the integer is used.
            Defaults to ``None``.
        __config__: The configuration of the new model.
        __doc__: The docstring of the new model.
        __module__: The name of the module that the model belongs to.
            If ``None``, the value is retrieved from ``sys._getframe(1)``.
        __validators__: A dictionary of class methods that validate fields.
        __cls_kwargs__: A dictionary of keyword arguments for class creation,
            such as ``metaclass``.
        discriminator: The discriminator either as a string or an object use
            for the validation of the discriminated root type.
        root: Root attributes of the new model. It should be passed in
            the format: ``<name>=(<type>, <default value>)`` or
            ``<name>=(<type>, <FieldInfo>)``.

    Returns:
        The new `DiscriminatedModel` class.

    Raises:
        ValueError: If `__base__` and `__config__` are both passed.
    """
    # Create the factory model class and update configuration
    model_config = __config__ or ModelConfig()
    class FactoryModel(
        DiscriminatedModel[*tuple[_TBase, ...]],
        discriminator=discriminator,
    ):
        __config__ = model_config
        __registrant__ = (
            id(__owner__)
            if __owner__ and not isinstance(__owner__, int)
            else __owner__
        )

    __base__ = typing.cast(
        type[DiscriminatedModel[*tuple[_TBase, ...]]],
        FactoryModel,
    )

    # Create model using Pydantic factory with updated configuration
    return _create_model(
        __model_name,
        __doc__=__doc__,
        __base__=__base__,
        __module__=__module__,  # type: ignore[arg-type]
        __validators__=__validators__,
        __cls_kwargs__=__cls_kwargs__,
        __slots__=None,
        root=root,
    )

collect_fields

collect_fields(
    __model: ModelType, **kwargs: Unpack[ModelFieldLookup]
) -> dict[str, tuple[type, ModelFieldInfo]]

Collect the model field definitions from the provided model.

It collects the model fields based on the provided model and keyword arguments lookup configuration to include or exclude specific fields. The collected fields annotations are updated with the provided partial flag, and the field information is updated with the provided default and update values. The field lookup configuration can be overridden to narrow down the field lookup configuration to specific fields.

Parameters:

Name Type Description Default
__model ModelType

The model class to collect the fields from.

required
**kwargs Unpack[ModelFieldLookup]

The field lookup configuration to collect the fields. - include: The filters to include specific fields based on the field attributes as a dictionary with the field attribute names as keys and the predicates to include as values. Defaults to None. - exclude: The filters to exclude specific fields based on the field attributes as a dictionary with the field attribute names as keys and the predicates to exclude as values. Defaults to None. - partial: Whether to mark the field annotations as optional. Defaults to None. - default: The default to apply and set within the field information. Defaults to None. - update: The update to apply and set within the field information. Defaults to None. - override: The field lookup configuration to override the current configuration. This can be used to narrow down the field lookup configuration to specific fields. Multiple levels of nested configurations can be provided and will be resolved recursively. Defaults to None.

{}

Returns:

Type Description
dict[str, tuple[type, ModelFieldInfo]]

A dictionary of field names with the corresponding field annotations

dict[str, tuple[type, ModelFieldInfo]]

and field information.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def collect_fields(
    __model: ModelType, **kwargs: Unpack[ModelFieldLookup],
) -> dict[str, tuple[type, ModelFieldInfo]]:
    """Collect the model field definitions from the provided model.

    It collects the model fields based on the provided model and keyword
    arguments lookup configuration to include or exclude specific fields. The
    collected fields annotations are updated with the provided `partial` flag,
    and the field information is updated with the provided `default` and
    `update` values. The field lookup configuration can be overridden to narrow
    down the field lookup configuration to specific fields.

    Args:
        __model: The model class to collect the fields from.
        **kwargs: The field lookup configuration to collect the fields.
            - `include`: The filters to include specific fields based on the
                field attributes as a dictionary with the field attribute names
                as keys and the predicates to include as values.
                Defaults to ``None``.
            - `exclude`: The filters to exclude specific fields based on the
                field attributes as a dictionary with the field attribute names
                as keys and the predicates to exclude as values.
                Defaults to ``None``.
            - `partial`: Whether to mark the field annotations as optional.
                Defaults to ``None``.
            - `default`: The default to apply and set within the field
                information. Defaults to ``None``.
            - `update`: The update to apply and set within the field
                information. Defaults to ``None``.
            - `override`: The field lookup configuration to override the
                current configuration. This can be used to narrow down the
                field lookup configuration to specific fields. Multiple levels
                of nested configurations can be provided and will be resolved
                recursively. Defaults to ``None``.

    Returns:
        A dictionary of field names with the corresponding field annotations
        and field information.
    """
    field_definitions: dict[str, tuple[type, ModelFieldInfo]] = {}

    if issubclass(__model, DiscriminatedModel):
        __model = __model.get_root_base()

    # Helper function to check if a field should be included or excluded
    def check(
        field: ModelFieldInfo,
        key: str,
        predicate: IncExPredicate,
    ) -> bool:
        # Retrieve field target attribute
        attr = field
        key_segments = key.split('.')
        for key_segment in key_segments:
            if not hasattr(attr, key_segment):
                return False
            attr = getattr(attr, key_segment)

        # Retrieve predicate information
        if isinstance(predicate, tuple):
            *check_callable, check_value = predicate
            if len(check_callable) == 2:
                check_args, check_kwargs = check_callable
            else:
                check_callable = check_callable[0]
                if isinstance(check_callable, Sequence):
                    check_args = check_callable
                    check_kwargs = {}
                elif isinstance(check_callable, Mapping):
                    check_args = ()
                    check_kwargs = check_callable
        else:
            check_args = ()
            check_kwargs = {}
            check_value = predicate

        # Check attribute value against the predicate
        if callable(attr):
            attr_value = attr(*check_args, **check_kwargs)
        else:
            attr_value = attr

        return bool(
            check_value in attr_value
            if isinstance(attr_value, (list, set, tuple))
            else check_value == attr_value
        )

    # Recursive function to process field lookup configuration
    def process_fields(
        lookup: ModelFieldLookup,
        *field_names: str,
    ) -> None:
        include = lookup.get('include', None)
        exclude = lookup.get('exclude', None)
        partial = lookup.get('partial', None)
        default = lookup.get('default', None)
        update = lookup.get('update', None)
        override = lookup.get('override', None)

        check_names: set[str] = set()

        for field_name in field_names:
            model_field = __model.model_fields[field_name]

            # Check if field should be included or excluded
            check_include = include is None or all(
                check(model_field, k, v) for k, v in include.items()
            )
            check_exclude = exclude is not None and any(
                check(model_field, k, v) for k, v in exclude.items()
            )

            # Process field if it should be included
            if check_include and not check_exclude:
                check_names.add(field_name)

                # Retrieve field definition
                if field_name not in field_definitions:
                    annotation = \
                        typing.cast(type, copy(model_field.annotation))
                    field = copy(model_field)
                    field._update(
                        annotation=None,
                        owner=Undefined,
                        name=Undefined,
                    )
                else:
                    annotation, field = field_definitions[field_name]

                # Update field definition
                if default:
                    field._default(**default)
                if update:
                    field._update(**update)
                if partial is True:
                    annotation = Optional[annotation]  # type: ignore
                    if field.default is Undefined \
                            and field.default_factory is None:
                        field._update(default=None)

                field_definitions[field_name] = (annotation, field)

        # Process nested field lookup configuration
        if check_names and override is not None:
            process_fields(override, *check_names)

    process_fields(kwargs, *__model.model_fields.keys())

    return field_definitions

collect_models

collect_models(
    __obj: Any,
    *,
    __config__: ModelConfig | None = None,
    __base__: ModelType
    | tuple[ModelType, ...]
    | None = None,
    __module__: str | None = None,
    __validators__: dict[str, ClassMethodType]
    | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    __namespace__: str | None = None,
) -> list[ModelType]

Collect and build recursively all nested models in a given object.

It recursively collect all nested classes in a given object and build the associated models. The __namespace__ argument is used recursively to determine the root namespace under which the models are collected.

Parameters:

Name Type Description Default
__obj Any

The object to inspect for nested classes.

required
__config__ ModelConfig | None

The configuration of the new models.

None
__base__ ModelType | tuple[ModelType, ...] | None

The base class or classes for the new models.

None
__module__ str | None

The name of the module that the models belongs to. If None, the value is retrieved from sys._getframe(1).

None
__validators__ dict[str, ClassMethodType] | None

A dictionary of class methods that validate fields.

None
__cls_kwargs__ dict[str, Any] | None

A dictionary of keyword arguments for class creation, such as metaclass.

None
__namespace__ str | None

The namespace of the object to collect models from.

None

Returns:

Type Description
list[ModelType]

A dictionary with the generated BaseModel classes.

Raises:

Type Description
ValueError

If __base__ and __config__ are both passed.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def collect_models(
    __obj: Any,
    *,
    __config__: ModelConfig | None = None,
    __base__: ModelType | tuple[ModelType, ...] | None = None,
    __module__: str | None = None,
    __validators__: dict[str, ClassMethodType] | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    __namespace__: str | None = None,
) -> list[ModelType]:
    """Collect and build recursively all nested models in a given object.

    It recursively collect all nested classes in a given object and build the
    associated models. The `__namespace__` argument is used recursively to
    determine the root namespace under which the models are collected.

    Args:
        __obj: The object to inspect for nested classes.
        __config__: The configuration of the new models.
        __base__: The base class or classes for the new models.
        __module__: The name of the module that the models belongs to.
            If ``None``, the value is retrieved from ``sys._getframe(1)``.
        __validators__: A dictionary of class methods that validate fields.
        __cls_kwargs__: A dictionary of keyword arguments for class creation,
            such as ``metaclass``.
        __namespace__: The namespace of the object to collect models from.

    Returns:
        A dictionary with the generated `BaseModel` classes.

    Raises:
        ValueError: If `__base__` and `__config__` are both passed.
    """
    # Retrieve object namespace
    obj_namespace = get_object_name(__obj, fullname=True) + '.'

    # Validate root and object namespace
    if __namespace__ is None:
        __namespace__ = obj_namespace
    if not obj_namespace.startswith(__namespace__):
        raise ValueError(
            f"Object namespace {obj_namespace!r} does not belong to the "
            f"specified namespace {__namespace__!r}."
        )

    models: list[ModelType] = []

    for name in dir(__obj):
        # Skip private and dunder attributes
        if name.startswith('_'):
            continue

        attr = getattr(__obj, name, None)

        # Skip non-class objects
        if not inspect.isclass(attr):
            continue

        # Skip non-defined classes
        attr_name = get_object_name(attr, fullname=True)
        if not attr_name.startswith(obj_namespace):
            continue

        # Build model
        model_name = attr_name[len(__namespace__):]
        if issubclass(attr, BaseModel):
            model = attr
        else:
            field_definitions = {}
            for field_name, field_type in attr.__annotations__.items():
                if field_name.startswith('_'):
                    continue
                field_value = ...
                if hasattr(attr, field_name):
                    field_value = getattr(attr, field_name)
                field_definitions[field_name] = (field_type, field_value)

            model = create_model(  # type: ignore
                model_name,
                __config__=__config__,
                __doc__=getattr(attr, '__doc__', None),
                __base__=__base__,  # type: ignore[arg-type]
                __module__=__module__,  # type: ignore[arg-type]
                __validators__=__validators__,
                __cls_kwargs__={
                    **(__cls_kwargs__ or {}),
                    'stub': has_stub_noop(attr),
                },
                **field_definitions,
            )

        # Add model
        models.append(model)

        # Add nested models
        nested_models = collect_models(
            attr,
            __config__=__config__,
            __base__=__base__,
            __module__=__module__,
            __validators__=__validators__,
            __cls_kwargs__=__cls_kwargs__,
            __namespace__=__namespace__,
        )
        models.extend(nested_models)

    return models