Skip to content

Fields

plateforme.core.schema.fields

This module provides utilities for managing fields information for configuration wrappers, models and resources within the Plateforme framework using Pydantic features.

The FieldInfo class is an extension of Pydantic's field information, it incorporates additional parameters like unique, linked, target, and others, enabling the definition of fields with extended behaviors specific to the Plateforme framework.

The Field and ConfigField function creates and extends field information with Pydantic's validation system, it allows the definition of configuration wrappers, models and resources attributes with additional behaviors specific to the Plateforme framework.

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 thenBaseModel and BaseResource for more information on data modeling features, including associations between models implemented into the field information.

SourceFieldInfoDict

Bases: TypedDict, Generic[Object]

A source field information dictionary.

A dictionary that holds the source configuration parameters for a field information instance. It is not meant to be exposed for parameterization to the user directly.

source instance-attribute

source: str | None

The source representation of the field definition. Defaults to None.

owner instance-attribute

owner: type[Object] | None

The owner of the field. It is inferred from the class where the field is defined if available else it defaults to None.

name instance-attribute

name: str | None

The name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None.

annotation instance-attribute

annotation: type[Any] | None

The type annotation of the field. Defaults to Undefined.

default instance-attribute

default: Any

The default value of the field. If not set and no default factory is provided, the field is considered required. Defaults to Undefined.

linked instance-attribute

linked: bool | None

Whether or not the field is linked. Defaults to None.

collection instance-attribute

collection: Literal['list', 'set'] | None

The collection type of the target association. It can be either an unconstrained collection list, or a collection of unique elements set, otherwise it defaults to None if the association is not a collection.

target instance-attribute

target: ResourceType | str | None

The linked field target BaseResource object type. Defaults to None.

association instance-attribute

association: Association | None

The Association object that defines the association between the owner and target resources. Defaults to None.

BaseFieldInfoDict

Bases: TypedDict

A base field information dictionary.

A dictionary that holds the base configuration parameters for a field information instance. It includes the basic parameters that are common to all field information instances.

default_factory instance-attribute

default_factory: Callable[[], Any] | None

The factory function used to construct the default value of the field. If both the default value and the default factory are set, an error is raised. Defaults to None.

alias instance-attribute

alias: str | None

The alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None.

alias_priority instance-attribute

alias_priority: int | None

The priority of the field's alias. This affects whether an alias generator is used or not. Defaults to None.

title instance-attribute

title: str | None

The human-readable name of the field. It must adhere to a specific TITLE pattern as defined in the framework's regular expressions repository. Defaults to None.

description instance-attribute

description: str | None

The description of the field. Defaults to None and uses the function's docstring if available.

examples instance-attribute

examples: list[Any] | None

List of examples of the field. Defaults to None.

deprecated instance-attribute

deprecated: Deprecated | str | bool | None

A deprecation message, an instance of Deprecated, or a boolean. If True, a default deprecation message will be emitted when accessing the field. Defaults to None.

frozen instance-attribute

frozen: bool | None

Whether or not the field is frozen. Defaults to None.

repr instance-attribute

repr: bool

Whether or not to include the field in the representation. Defaults to True.

init instance-attribute

init: bool

Whether the field should be included in the constructor of the dataclass. Defaults to True.

init_var instance-attribute

init_var: bool | None

Whether the field should only be included in the constructor of the dataclass, and not stored. Defaults to None.

kw_only instance-attribute

kw_only: bool | None

Whether or not the field should be a keyword-only argument in the constructor of the model. Defaults to None.

ModelFieldInfoDict

Bases: TypedDict

A model field information dictionary.

A dictionary that holds the model configuration parameters for a field information instance. It includes additional parameters that are specific to Pydantic field information.

validation_alias instance-attribute

validation_alias: str | AliasPath | AliasChoices | None

The validation alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None (alias name of the field).

serialization_alias instance-attribute

serialization_alias: str | None

The serialization alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None (alias name of the field).

exclude instance-attribute

exclude: bool | None

Whether or not to exclude the field from the model serialization. Defaults to None.

discriminator instance-attribute

discriminator: str | Discriminator | None

Field name for discriminating the type in a tagged union. Defaults to None.

json_schema_extra instance-attribute

json_schema_extra: JsonSchemaExtra | None

Dictionary or callable to provide extra JSON schema properties. Defaults to None.

validate_default instance-attribute

validate_default: bool | None

Whether or not to validate the default value of the field. Defaults to None.

pattern instance-attribute

pattern: str | None

A regular expression pattern that the field value must match. Defaults to None.

strict instance-attribute

strict: bool | None

Whether or not to enforce strict validation of the field value. Defaults to None.

gt instance-attribute

gt: float | None

The minimum value of the field. Defaults to None.

ge instance-attribute

ge: float | None

The minimum value of the field, inclusive. Defaults to None.

lt instance-attribute

lt: float | None

The maximum value of the field. Defaults to None.

le instance-attribute

le: float | None

The maximum value of the field, inclusive. Defaults to None.

multiple_of instance-attribute

multiple_of: float | None

The value must be a multiple of this number. Defaults to None.

allow_inf_nan instance-attribute

allow_inf_nan: bool | None

Whether or not to allow infinity and NaN values. Defaults to None.

max_digits instance-attribute

max_digits: int | None

The maximum number of digits in the field value. Defaults to None.

decimal_places instance-attribute

decimal_places: int | None

The number of decimal places in the field value. Defaults to None.

min_length instance-attribute

min_length: int | None

The minimum length of the field value. Defaults to None.

max_length instance-attribute

max_length: int | None

The maximum length of the field value. Defaults to None.

union_mode instance-attribute

union_mode: Literal['smart', 'left_to_right'] | None

The union mode for the field value. Defaults to None.

recursive_guard instance-attribute

recursive_guard: str | None

A recursive guard to handle infinite recursion when validating and serializing fields. Defaults to None.

ResourceFieldInfoDict

Bases: TypedDict

A resource field information dictionary.

A dictionary that holds the resource configuration parameters for a field information instance. It includes additional parameters that are specific to resource field information within the Plateforme framework.

slug instance-attribute

slug: str | None

The slug name of the field. It must adhere to a specific SLUG pattern as defined in the framework's regular expressions repository. Defaults to None.

unique instance-attribute

unique: bool | None

Whether or not the field is unique. Defaults to None.

indexed instance-attribute

indexed: bool | None

Whether or not the field is indexed. Defaults to None.

target_ref instance-attribute

target_ref: bool | None

Whether the field can accept a reference to the target resource instead of the resource schema model itself. Defaults to None.

target_schemas instance-attribute

target_schemas: tuple[str, ...] | bool | None

Either a tuple of the linked field target DiscriminatedModel schema models to use for the annotation resolution, or a boolean to indicate whether the target schema models should be resolved. Defaults to None.

association_alias instance-attribute

association_alias: str | None

The association alias identifier. By default, this is determined by concatenating the owner and target resource alias with an underscore (see the Association class). Defaults to None.

rel_attribute instance-attribute

rel_attribute: str | None

The attribute name of the foreign key column implemented within the owner resource. This is optional and only applies in a scenario where a foreign key column is required for managing the association. If the field is not linked or the association (like a many-to-many association) does not require a direct foreign key column, this parameter defaults to None. Conversely, if a link exists and the association necessitates a foreign key column (as per the two-way association analysis), this parameter defaults to the alias of the linked field, appended with _id. Defaults to None.

rel_backref instance-attribute

rel_backref: BackrefFieldInfoDict | None

The corresponding back referencing target linked field counterpart of the association. This argument can be used to define a back reference configuration using a BackrefFieldInfoDict dictionary when no counterpart exists in the target resource. This is useful in scenarios where there is no control over the target resource definition, and the back reference must be implemented in the owner resource. Otherwise, it is recommended to define the back reference directly in the target resource. If the target resource does not have a counterpart linked field defined for the given association, the field information attribute initializes to None, otherwise it stores the target counterpart ResourceFieldInfo instance, either generated from the target resourcedefinition, or by the provided back reference dictionary configuration. Defaults to None.

rel_cascade instance-attribute

rel_cascade: str | bool | None

The cascade options for the relationship. The possible cascading options are 'delete', 'delete-orphan', 'expunge', 'merge', 'refresh-expire', 'save-update', and all, where the latter is a shorthand for 'save-update, merge, refresh-expire, expunge, delete', and is often used as in 'all, delete-orphan' to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated. Defaults to None for non-linked fields, otherwise True for linked fields which resolves to: - 'save-update, merge' when the association is bidirectional, - '..., delete, delete-orphan' when the target resource link is identifying, - '..., refresh-expire, expunge' when the target resource link is indexing.

rel_load instance-attribute

rel_load: LoadRule | bool | None

The lazy loading options for the relationship. Defaults to None for non-linked fields, otherwise True for linked fields which resolves to: - 'joined' when the association is indexing one of the resources, - 'selectin' when the resource owner field is not a collection, - 'select' otherwise (lazy loading).

rel_extra instance-attribute

rel_extra: dict[str, Any] | None

Additional association relationship configuration parameters. Defaults to None.

column_extra instance-attribute

column_extra: dict[str, Any] | None

Additional column configuration parameters. Defaults to None.

data_type instance-attribute

data_type: TypeEngine | None

The data type engine to use for the field. It is automatically inferred from the field annotation if not explicitly set. Defaults to None.

data_collation instance-attribute

data_collation: str | None

The collation of the field used for strings within the database. Defaults to None.

data_none_as_null instance-attribute

data_none_as_null: bool | None

Whether or not to treat None as NULL in the database for JSON data types. Defaults to None.

data_extra instance-attribute

data_extra: dict[str, Any] | None

Additional data column configuration parameters. Defaults to None.

BackrefFieldInfoDict

Bases: TypedDict

A backref field information configuration dictionary.

A dictionary that holds the configuration parameters for a field information back reference instance. It is used to define the keyword arguments when creating a field information in a scenario where the target resource does not have a counterpart linked field for a given association.

name instance-attribute

name: str | None

The name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None.

default instance-attribute

default: Any

The default value of the field. If not set and no default factory is provided, the field is considered required. Defaults to Undefined.

default_factory instance-attribute

default_factory: Callable[[], Any] | None

The factory function used to construct the default value of the field. If both the default value and the default factory are set, an error is raised. Defaults to None.

alias instance-attribute

alias: str | None

The alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None.

alias_priority instance-attribute

alias_priority: int | None

The priority of the field's alias. This affects whether an alias generator is used or not. Defaults to None.

title instance-attribute

title: str | None

The human-readable name of the field. It must adhere to a specific TITLE pattern as defined in the framework's regular expressions repository. Defaults to None.

description instance-attribute

description: str | None

The description of the field. Defaults to None and uses the function's docstring if available.

examples instance-attribute

examples: list[Any] | None

List of examples of the field. Defaults to None.

deprecated instance-attribute

deprecated: Deprecated | str | bool | None

A deprecation message, an instance of Deprecated, or a boolean. If True, a default deprecation message will be emitted when accessing the field. Defaults to None.

frozen instance-attribute

frozen: bool | None

Whether or not the field is frozen. Defaults to None.

repr instance-attribute

repr: bool

Whether or not to include the field in the representation. Defaults to True.

init instance-attribute

init: bool

Whether the field should be included in the constructor of the dataclass. Defaults to True.

init_var instance-attribute

init_var: bool | None

Whether the field should only be included in the constructor of the dataclass, and not stored. Defaults to None.

kw_only instance-attribute

kw_only: bool | None

Whether or not the field should be a keyword-only argument in the constructor of the model. Defaults to None.

validation_alias instance-attribute

validation_alias: str | AliasPath | AliasChoices | None

The validation alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None (alias name of the field).

serialization_alias instance-attribute

serialization_alias: str | None

The serialization alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None (alias name of the field).

exclude instance-attribute

exclude: bool | None

Whether or not to exclude the field from the model serialization. Defaults to None.

discriminator instance-attribute

discriminator: str | Discriminator | None

Field name for discriminating the type in a tagged union. Defaults to None.

json_schema_extra instance-attribute

json_schema_extra: JsonSchemaExtra | None

Dictionary or callable to provide extra JSON schema properties. Defaults to None.

validate_default instance-attribute

validate_default: bool | None

Whether or not to validate the default value of the field. Defaults to None.

recursive_guard instance-attribute

recursive_guard: str | None

A recursive guard to handle infinite recursion when validating and serializing fields. Defaults to None.

slug instance-attribute

slug: str | None

The slug name of the field. It must adhere to a specific SLUG pattern as defined in the framework's regular expressions repository. Defaults to None.

unique instance-attribute

unique: bool | None

Whether or not the field is unique. Defaults to None.

indexed instance-attribute

indexed: bool | None

Whether or not the field is indexed. Defaults to None.

collection instance-attribute

collection: Literal['list', 'set'] | None

The collection type of the target association. It can be either an unconstrained collection list, or a collection of unique elements set, otherwise it defaults to None if the association is not a collection.

rel_attribute instance-attribute

rel_attribute: str | None

The attribute name of the foreign key column implemented within the owner resource. This is optional and only applies in a scenario where a foreign key column is required for managing the association. If the field is not linked or the association (like a many-to-many association) does not require a direct foreign key column, this parameter defaults to None. Conversely, if a link exists and the association necessitates a foreign key column (as per the two-way association analysis), this parameter defaults to the alias of the linked field, appended with _id. Defaults to None.

rel_cascade instance-attribute

rel_cascade: str | bool | None

The cascade options for the relationship. The possible cascading options are 'delete', 'delete-orphan', 'expunge', 'merge', 'refresh-expire', 'save-update', and all, where the latter is a shorthand for 'save-update, merge, refresh-expire, expunge, delete', and is often used as in 'all, delete-orphan' to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated. Defaults to None for non-linked fields, otherwise True for linked fields which resolves to: - 'save-update, merge' when the association is bidirectional, - '..., delete, delete-orphan' when the target resource link is identifying, - '..., refresh-expire, expunge' when the target resource link is indexing.

rel_load instance-attribute

rel_load: LoadRule | bool | None

The lazy loading options for the relationship. Defaults to None for non-linked fields, otherwise True for linked fields which resolves to: - 'joined' when the association is indexing one of the resources, - 'selectin' when the resource owner field is not a collection, - 'select' otherwise (lazy loading).

rel_extra instance-attribute

rel_extra: dict[str, Any] | None

Additional association relationship configuration parameters. Defaults to None.

column_extra instance-attribute

column_extra: dict[str, Any] | None

Additional column configuration parameters. Defaults to None.

FieldInfoDict

Bases: SourceFieldInfoDict[Object], BaseFieldInfoDict, ModelFieldInfoDict, ResourceFieldInfoDict, Generic[Object]

A global field information configuration dictionary.

A dictionary that provides all the configuration parameters for a field information instance within the Plateforme framework. It combines the SourceFieldInfoDict, BaseFieldInfoDict, ModelFieldInfoDict, and ResourceFieldInfoDict configuration dictionaries into a single comprehensive dictionary.

slug instance-attribute

slug: str | None

The slug name of the field. It must adhere to a specific SLUG pattern as defined in the framework's regular expressions repository. Defaults to None.

unique instance-attribute

unique: bool | None

Whether or not the field is unique. Defaults to None.

indexed instance-attribute

indexed: bool | None

Whether or not the field is indexed. Defaults to None.

target_ref instance-attribute

target_ref: bool | None

Whether the field can accept a reference to the target resource instead of the resource schema model itself. Defaults to None.

target_schemas instance-attribute

target_schemas: tuple[str, ...] | bool | None

Either a tuple of the linked field target DiscriminatedModel schema models to use for the annotation resolution, or a boolean to indicate whether the target schema models should be resolved. Defaults to None.

association_alias instance-attribute

association_alias: str | None

The association alias identifier. By default, this is determined by concatenating the owner and target resource alias with an underscore (see the Association class). Defaults to None.

rel_attribute instance-attribute

rel_attribute: str | None

The attribute name of the foreign key column implemented within the owner resource. This is optional and only applies in a scenario where a foreign key column is required for managing the association. If the field is not linked or the association (like a many-to-many association) does not require a direct foreign key column, this parameter defaults to None. Conversely, if a link exists and the association necessitates a foreign key column (as per the two-way association analysis), this parameter defaults to the alias of the linked field, appended with _id. Defaults to None.

rel_backref instance-attribute

rel_backref: BackrefFieldInfoDict | None

The corresponding back referencing target linked field counterpart of the association. This argument can be used to define a back reference configuration using a BackrefFieldInfoDict dictionary when no counterpart exists in the target resource. This is useful in scenarios where there is no control over the target resource definition, and the back reference must be implemented in the owner resource. Otherwise, it is recommended to define the back reference directly in the target resource. If the target resource does not have a counterpart linked field defined for the given association, the field information attribute initializes to None, otherwise it stores the target counterpart ResourceFieldInfo instance, either generated from the target resourcedefinition, or by the provided back reference dictionary configuration. Defaults to None.

rel_cascade instance-attribute

rel_cascade: str | bool | None

The cascade options for the relationship. The possible cascading options are 'delete', 'delete-orphan', 'expunge', 'merge', 'refresh-expire', 'save-update', and all, where the latter is a shorthand for 'save-update, merge, refresh-expire, expunge, delete', and is often used as in 'all, delete-orphan' to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated. Defaults to None for non-linked fields, otherwise True for linked fields which resolves to: - 'save-update, merge' when the association is bidirectional, - '..., delete, delete-orphan' when the target resource link is identifying, - '..., refresh-expire, expunge' when the target resource link is indexing.

rel_load instance-attribute

rel_load: LoadRule | bool | None

The lazy loading options for the relationship. Defaults to None for non-linked fields, otherwise True for linked fields which resolves to: - 'joined' when the association is indexing one of the resources, - 'selectin' when the resource owner field is not a collection, - 'select' otherwise (lazy loading).

rel_extra instance-attribute

rel_extra: dict[str, Any] | None

Additional association relationship configuration parameters. Defaults to None.

column_extra instance-attribute

column_extra: dict[str, Any] | None

Additional column configuration parameters. Defaults to None.

data_type instance-attribute

data_type: TypeEngine | None

The data type engine to use for the field. It is automatically inferred from the field annotation if not explicitly set. Defaults to None.

data_collation instance-attribute

data_collation: str | None

The collation of the field used for strings within the database. Defaults to None.

data_none_as_null instance-attribute

data_none_as_null: bool | None

Whether or not to treat None as NULL in the database for JSON data types. Defaults to None.

data_extra instance-attribute

data_extra: dict[str, Any] | None

Additional data column configuration parameters. Defaults to None.

validation_alias instance-attribute

validation_alias: str | AliasPath | AliasChoices | None

The validation alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None (alias name of the field).

serialization_alias instance-attribute

serialization_alias: str | None

The serialization alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None (alias name of the field).

exclude instance-attribute

exclude: bool | None

Whether or not to exclude the field from the model serialization. Defaults to None.

discriminator instance-attribute

discriminator: str | Discriminator | None

Field name for discriminating the type in a tagged union. Defaults to None.

json_schema_extra instance-attribute

json_schema_extra: JsonSchemaExtra | None

Dictionary or callable to provide extra JSON schema properties. Defaults to None.

validate_default instance-attribute

validate_default: bool | None

Whether or not to validate the default value of the field. Defaults to None.

pattern instance-attribute

pattern: str | None

A regular expression pattern that the field value must match. Defaults to None.

strict instance-attribute

strict: bool | None

Whether or not to enforce strict validation of the field value. Defaults to None.

gt instance-attribute

gt: float | None

The minimum value of the field. Defaults to None.

ge instance-attribute

ge: float | None

The minimum value of the field, inclusive. Defaults to None.

lt instance-attribute

lt: float | None

The maximum value of the field. Defaults to None.

le instance-attribute

le: float | None

The maximum value of the field, inclusive. Defaults to None.

multiple_of instance-attribute

multiple_of: float | None

The value must be a multiple of this number. Defaults to None.

allow_inf_nan instance-attribute

allow_inf_nan: bool | None

Whether or not to allow infinity and NaN values. Defaults to None.

max_digits instance-attribute

max_digits: int | None

The maximum number of digits in the field value. Defaults to None.

decimal_places instance-attribute

decimal_places: int | None

The number of decimal places in the field value. Defaults to None.

min_length instance-attribute

min_length: int | None

The minimum length of the field value. Defaults to None.

max_length instance-attribute

max_length: int | None

The maximum length of the field value. Defaults to None.

union_mode instance-attribute

union_mode: Literal['smart', 'left_to_right'] | None

The union mode for the field value. Defaults to None.

recursive_guard instance-attribute

recursive_guard: str | None

A recursive guard to handle infinite recursion when validating and serializing fields. Defaults to None.

default_factory instance-attribute

default_factory: Callable[[], Any] | None

The factory function used to construct the default value of the field. If both the default value and the default factory are set, an error is raised. Defaults to None.

alias instance-attribute

alias: str | None

The alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None.

alias_priority instance-attribute

alias_priority: int | None

The priority of the field's alias. This affects whether an alias generator is used or not. Defaults to None.

title instance-attribute

title: str | None

The human-readable name of the field. It must adhere to a specific TITLE pattern as defined in the framework's regular expressions repository. Defaults to None.

description instance-attribute

description: str | None

The description of the field. Defaults to None and uses the function's docstring if available.

examples instance-attribute

examples: list[Any] | None

List of examples of the field. Defaults to None.

deprecated instance-attribute

deprecated: Deprecated | str | bool | None

A deprecation message, an instance of Deprecated, or a boolean. If True, a default deprecation message will be emitted when accessing the field. Defaults to None.

frozen instance-attribute

frozen: bool | None

Whether or not the field is frozen. Defaults to None.

repr instance-attribute

repr: bool

Whether or not to include the field in the representation. Defaults to True.

init instance-attribute

init: bool

Whether the field should be included in the constructor of the dataclass. Defaults to True.

init_var instance-attribute

init_var: bool | None

Whether the field should only be included in the constructor of the dataclass, and not stored. Defaults to None.

kw_only instance-attribute

kw_only: bool | None

Whether or not the field should be a keyword-only argument in the constructor of the model. Defaults to None.

source instance-attribute

source: str | None

The source representation of the field definition. Defaults to None.

owner instance-attribute

owner: type[Object] | None

The owner of the field. It is inferred from the class where the field is defined if available else it defaults to None.

name instance-attribute

name: str | None

The name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None.

annotation instance-attribute

annotation: type[Any] | None

The type annotation of the field. Defaults to Undefined.

default instance-attribute

default: Any

The default value of the field. If not set and no default factory is provided, the field is considered required. Defaults to Undefined.

linked instance-attribute

linked: bool | None

Whether or not the field is linked. Defaults to None.

collection instance-attribute

collection: Literal['list', 'set'] | None

The collection type of the target association. It can be either an unconstrained collection list, or a collection of unique elements set, otherwise it defaults to None if the association is not a collection.

target instance-attribute

target: ResourceType | str | None

The linked field target BaseResource object type. Defaults to None.

association instance-attribute

association: Association | None

The Association object that defines the association between the owner and target resources. Defaults to None.

FieldInfoFromConfigDict

Bases: BaseFieldInfoDict

A field information configuration dictionary for a config function.

It is used to define a field information instance with the ConfigField function for configuration wrappers.

default_factory instance-attribute

default_factory: Callable[[], Any] | None

The factory function used to construct the default value of the field. If both the default value and the default factory are set, an error is raised. Defaults to None.

alias instance-attribute

alias: str | None

The alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None.

alias_priority instance-attribute

alias_priority: int | None

The priority of the field's alias. This affects whether an alias generator is used or not. Defaults to None.

title instance-attribute

title: str | None

The human-readable name of the field. It must adhere to a specific TITLE pattern as defined in the framework's regular expressions repository. Defaults to None.

description instance-attribute

description: str | None

The description of the field. Defaults to None and uses the function's docstring if available.

examples instance-attribute

examples: list[Any] | None

List of examples of the field. Defaults to None.

deprecated instance-attribute

deprecated: Deprecated | str | bool | None

A deprecation message, an instance of Deprecated, or a boolean. If True, a default deprecation message will be emitted when accessing the field. Defaults to None.

frozen instance-attribute

frozen: bool | None

Whether or not the field is frozen. Defaults to None.

repr instance-attribute

repr: bool

Whether or not to include the field in the representation. Defaults to True.

init instance-attribute

init: bool

Whether the field should be included in the constructor of the dataclass. Defaults to True.

init_var instance-attribute

init_var: bool | None

Whether the field should only be included in the constructor of the dataclass, and not stored. Defaults to None.

kw_only instance-attribute

kw_only: bool | None

Whether or not the field should be a keyword-only argument in the constructor of the model. Defaults to None.

FieldInfoFromFieldDict

Bases: BaseFieldInfoDict, ModelFieldInfoDict, ResourceFieldInfoDict

A field information configuration dictionary for a field function.

It is used to define a field information instance with the Field function for models and resources.

slug instance-attribute

slug: str | None

The slug name of the field. It must adhere to a specific SLUG pattern as defined in the framework's regular expressions repository. Defaults to None.

unique instance-attribute

unique: bool | None

Whether or not the field is unique. Defaults to None.

indexed instance-attribute

indexed: bool | None

Whether or not the field is indexed. Defaults to None.

target_ref instance-attribute

target_ref: bool | None

Whether the field can accept a reference to the target resource instead of the resource schema model itself. Defaults to None.

target_schemas instance-attribute

target_schemas: tuple[str, ...] | bool | None

Either a tuple of the linked field target DiscriminatedModel schema models to use for the annotation resolution, or a boolean to indicate whether the target schema models should be resolved. Defaults to None.

association_alias instance-attribute

association_alias: str | None

The association alias identifier. By default, this is determined by concatenating the owner and target resource alias with an underscore (see the Association class). Defaults to None.

rel_attribute instance-attribute

rel_attribute: str | None

The attribute name of the foreign key column implemented within the owner resource. This is optional and only applies in a scenario where a foreign key column is required for managing the association. If the field is not linked or the association (like a many-to-many association) does not require a direct foreign key column, this parameter defaults to None. Conversely, if a link exists and the association necessitates a foreign key column (as per the two-way association analysis), this parameter defaults to the alias of the linked field, appended with _id. Defaults to None.

rel_backref instance-attribute

rel_backref: BackrefFieldInfoDict | None

The corresponding back referencing target linked field counterpart of the association. This argument can be used to define a back reference configuration using a BackrefFieldInfoDict dictionary when no counterpart exists in the target resource. This is useful in scenarios where there is no control over the target resource definition, and the back reference must be implemented in the owner resource. Otherwise, it is recommended to define the back reference directly in the target resource. If the target resource does not have a counterpart linked field defined for the given association, the field information attribute initializes to None, otherwise it stores the target counterpart ResourceFieldInfo instance, either generated from the target resourcedefinition, or by the provided back reference dictionary configuration. Defaults to None.

rel_cascade instance-attribute

rel_cascade: str | bool | None

The cascade options for the relationship. The possible cascading options are 'delete', 'delete-orphan', 'expunge', 'merge', 'refresh-expire', 'save-update', and all, where the latter is a shorthand for 'save-update, merge, refresh-expire, expunge, delete', and is often used as in 'all, delete-orphan' to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated. Defaults to None for non-linked fields, otherwise True for linked fields which resolves to: - 'save-update, merge' when the association is bidirectional, - '..., delete, delete-orphan' when the target resource link is identifying, - '..., refresh-expire, expunge' when the target resource link is indexing.

rel_load instance-attribute

rel_load: LoadRule | bool | None

The lazy loading options for the relationship. Defaults to None for non-linked fields, otherwise True for linked fields which resolves to: - 'joined' when the association is indexing one of the resources, - 'selectin' when the resource owner field is not a collection, - 'select' otherwise (lazy loading).

rel_extra instance-attribute

rel_extra: dict[str, Any] | None

Additional association relationship configuration parameters. Defaults to None.

column_extra instance-attribute

column_extra: dict[str, Any] | None

Additional column configuration parameters. Defaults to None.

data_type instance-attribute

data_type: TypeEngine | None

The data type engine to use for the field. It is automatically inferred from the field annotation if not explicitly set. Defaults to None.

data_collation instance-attribute

data_collation: str | None

The collation of the field used for strings within the database. Defaults to None.

data_none_as_null instance-attribute

data_none_as_null: bool | None

Whether or not to treat None as NULL in the database for JSON data types. Defaults to None.

data_extra instance-attribute

data_extra: dict[str, Any] | None

Additional data column configuration parameters. Defaults to None.

validation_alias instance-attribute

validation_alias: str | AliasPath | AliasChoices | None

The validation alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None (alias name of the field).

serialization_alias instance-attribute

serialization_alias: str | None

The serialization alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None (alias name of the field).

exclude instance-attribute

exclude: bool | None

Whether or not to exclude the field from the model serialization. Defaults to None.

discriminator instance-attribute

discriminator: str | Discriminator | None

Field name for discriminating the type in a tagged union. Defaults to None.

json_schema_extra instance-attribute

json_schema_extra: JsonSchemaExtra | None

Dictionary or callable to provide extra JSON schema properties. Defaults to None.

validate_default instance-attribute

validate_default: bool | None

Whether or not to validate the default value of the field. Defaults to None.

pattern instance-attribute

pattern: str | None

A regular expression pattern that the field value must match. Defaults to None.

strict instance-attribute

strict: bool | None

Whether or not to enforce strict validation of the field value. Defaults to None.

gt instance-attribute

gt: float | None

The minimum value of the field. Defaults to None.

ge instance-attribute

ge: float | None

The minimum value of the field, inclusive. Defaults to None.

lt instance-attribute

lt: float | None

The maximum value of the field. Defaults to None.

le instance-attribute

le: float | None

The maximum value of the field, inclusive. Defaults to None.

multiple_of instance-attribute

multiple_of: float | None

The value must be a multiple of this number. Defaults to None.

allow_inf_nan instance-attribute

allow_inf_nan: bool | None

Whether or not to allow infinity and NaN values. Defaults to None.

max_digits instance-attribute

max_digits: int | None

The maximum number of digits in the field value. Defaults to None.

decimal_places instance-attribute

decimal_places: int | None

The number of decimal places in the field value. Defaults to None.

min_length instance-attribute

min_length: int | None

The minimum length of the field value. Defaults to None.

max_length instance-attribute

max_length: int | None

The maximum length of the field value. Defaults to None.

union_mode instance-attribute

union_mode: Literal['smart', 'left_to_right'] | None

The union mode for the field value. Defaults to None.

recursive_guard instance-attribute

recursive_guard: str | None

A recursive guard to handle infinite recursion when validating and serializing fields. Defaults to None.

default_factory instance-attribute

default_factory: Callable[[], Any] | None

The factory function used to construct the default value of the field. If both the default value and the default factory are set, an error is raised. Defaults to None.

alias instance-attribute

alias: str | None

The alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None.

alias_priority instance-attribute

alias_priority: int | None

The priority of the field's alias. This affects whether an alias generator is used or not. Defaults to None.

title instance-attribute

title: str | None

The human-readable name of the field. It must adhere to a specific TITLE pattern as defined in the framework's regular expressions repository. Defaults to None.

description instance-attribute

description: str | None

The description of the field. Defaults to None and uses the function's docstring if available.

examples instance-attribute

examples: list[Any] | None

List of examples of the field. Defaults to None.

deprecated instance-attribute

deprecated: Deprecated | str | bool | None

A deprecation message, an instance of Deprecated, or a boolean. If True, a default deprecation message will be emitted when accessing the field. Defaults to None.

frozen instance-attribute

frozen: bool | None

Whether or not the field is frozen. Defaults to None.

repr instance-attribute

repr: bool

Whether or not to include the field in the representation. Defaults to True.

init instance-attribute

init: bool

Whether the field should be included in the constructor of the dataclass. Defaults to True.

init_var instance-attribute

init_var: bool | None

Whether the field should only be included in the constructor of the dataclass, and not stored. Defaults to None.

kw_only instance-attribute

kw_only: bool | None

Whether or not the field should be a keyword-only argument in the constructor of the model. Defaults to None.

FieldInfoMeta

Bases: type

Meta class for the field information class.

FieldInfo

FieldInfo(**kwargs: Unpack[FieldInfoDict[Any]])

Bases: Representation, FieldInfo, Generic[Object]

A field information.

A class that holds information about a field. The FieldInfo class is used however a field is defined, whether or not a field function is explicitly used within a BaseModel, BaseResource, or ConfigWrapper subclass.

Attributes:

Name Type Description
source str | None

The source representation of the field definition. Defaults to None.

owner type[Object]

The owner of the field. It is inferred from the class where the field is defined if available else it defaults to None.

name str

The name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. It is inferred from the owner class field attribute name converted to snake case.

annotation type[Any] | None

The type annotation of the field. Defaults to Undefined.

default Any

The default value of the field. If not set and no default factory is provided, the field is considered required. Defaults to Undefined.

default_factory Callable[[], Any] | None

The factory function used to construct the default value of the field. If both the default value and the default factory are set, an error is raised. Defaults to None.

alias str

The alias name of the field. 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 field identifier.

alias_priority int | None

The priority of the field's alias. This affects whether an alias generator is used or not. Defaults to None.

title str

The human-readable name of the field. 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 field identifier.

description str | None

The description of the field. Defaults to None and uses the function's docstring if available.

examples list[Any] | None

List of examples of the field. Defaults to None.

deprecated Deprecated | str | bool | None

A deprecation message, an instance of Deprecated, or a boolean. If True, a default deprecation message will be emitted when accessing the field. Defaults to None.

frozen bool | None

Whether or not the field is frozen. Defaults to None.

repr bool

Whether or not to include the field in the representation. Defaults to True.

init bool

Whether the field should be included in the constructor of the dataclass. Defaults to True.

init_var bool | None

Whether the field should only be included in the constructor of the dataclass, and not stored. Defaults to None.

kw_only bool | None

Whether or not the field should be a keyword-only argument in the constructor of the model. Defaults to None.

validation_alias str | AliasPath | AliasChoices | None

The validation alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None (alias name of the field).

serialization_alias str | None

The serialization alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. Defaults to None (alias name of the field).

exclude bool | None

Whether or not to exclude the field from the model serialization. Defaults to None.

discriminator str | Discriminator | None

Field name for discriminating the type in a tagged union. Defaults to None.

json_schema_extra JsonSchemaExtra | None

Dictionary or callable to provide extra JSON schema properties. Defaults to None.

validate_default bool | None

Whether or not to validate the default value of the field. Defaults to None.

metadata list[Any]

List of metadata constraints. Defaults to an empty list.

recursive_guard str | None

A recursive guard to handle infinite recursion when validating and serializing fields. Defaults to None.

slug str

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

unique bool | None

Whether or not the field is unique. Defaults to None.

indexed bool | None

Whether or not the field is indexed. Defaults to None.

linked bool | None

Whether or not the field is linked. Defaults to None.

collection Literal['list', 'set'] | None

The collection type of the target association. It can be either an unconstrained collection list, or a collection of unique elements set, otherwise it defaults to None if the association is not a collection.

target ResourceType | str | None

The linked field target BaseResource object type. Defaults to None.

target_ref bool | None

Whether the field can accept a reference to the target resource instead of the resource schema model itself. Defaults to None.

target_schemas tuple[str, ...] | bool | None

Either a tuple of the linked field target DiscriminatedModel schema models to use for the annotation resolution, or a boolean to indicate whether the target schema models should be resolved. Defaults to None.

association Association | None

The Association object that defines the association between the owner and target resources. Defaults to None.

association_alias str | None

The association alias identifier. By default, this is determined by concatenating the owner and target resource alias with an underscore (see the Association class). Defaults to None.

rel_attribute str | None

The attribute name of the foreign key column implemented within the owner resource. This is optional and only applies in a scenario where a foreign key column is required for managing the association. If the field is not linked or the association (like a many-to-many association) does not require a direct foreign key column, this parameter defaults to None. Conversely, if a link exists and the association necessitates a foreign key column (as per the two-way association analysis), this parameter defaults to the alias of the linked field, appended with _id. Defaults to None.

rel_backref ResourceFieldInfo | None

The corresponding back referencing target linked field counterpart of the association. If the target resource does not have a counterpart linked field defined for the given association, it initializes to None, otherwise it stores the target counterpart ResourceFieldInfo instance, either generated from the target resource definition, or by the provided back reference BackrefFieldInfoDict dictionary configuration. Defaults to None.

rel_cascade str | bool | None

The cascade options for the relationship. The possible cascading options are 'delete', 'delete-orphan', 'expunge', 'merge', 'refresh-expire', 'save-update', and all, where the latter is a shorthand for 'save-update, merge, refresh-expire, expunge, delete', and is often used as in 'all, delete-orphan' to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated. Defaults to None for non-linked fields, otherwise True for linked fields which resolves to: - 'save-update, merge' when the association is bidirectional, - '..., delete, delete-orphan' when the target resource link is identifying, - '..., refresh-expire, expunge' when the target resource link is indexing.

rel_load LoadRule | bool | None

The lazy loading options for the relationship. Defaults to None for non-linked fields, otherwise True for linked fields which resolves to: - 'joined' when the association is indexing one of the resources, - 'selectin' when the resource owner field is not a collection, - 'select' otherwise (lazy loading).

rel_extra dict[str, Any] | None

Additional association relationship configuration parameters. Defaults to None.

column_extra dict[str, Any] | None

Additional column configuration parameters. Defaults to None.

data_type TypeEngine | None

The data type engine to use for the field. It is automatically inferred from the field annotation if not explicitly set. Defaults to None.

data_collation str | None

The collation of the field used for strings within the database. Defaults to None.

data_none_as_null bool | None

Whether or not to treat None as NULL in the database for JSON data types. Defaults to None.

data_extra dict[str, Any] | None

Additional data column configuration parameters. Defaults to None.

Initialize the field information.

It initializes the field information instance with the given keyword arguments. This constructor is not meant to be called directly, use the field functions like Field for models and resources, or ConfigField for configuration wrappers instead to create a field information instance.

Parameters:

Name Type Description Default
**kwargs Unpack[FieldInfoDict[Any]]

Additional keyword arguments. See the field information configuration dictionary FieldInfoDict for more information on the expected keyword arguments.

{}
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def __init__(self, **kwargs: Unpack[FieldInfoDict[Any]]) -> None:
    """Initialize the field information.

    It initializes the field information instance with the given keyword
    arguments. This constructor is not meant to be called directly, use the
    field functions like `Field` for models and resources, or `ConfigField`
    for configuration wrappers instead to create a field information
    instance.

    Args:
        **kwargs: Additional keyword arguments. See the field information
            configuration dictionary `FieldInfoDict` for more information
            on the expected keyword arguments.
    """
    # Clean up undefined keyword arguments
    kwargs_set = {k: v for k, v in kwargs.items() if v is not Undefined}
    kwargs_copy: dict[str, Any] = {**kwargs_set}

    # Store attributes set
    self._attributes_set = kwargs_set
    self._complete = False

    # Set field default values
    self.default = kwargs_copy.pop('default', Undefined)
    self.default_factory = kwargs_copy.pop('default_factory', None)
    # Check if default values are valid
    if self.default is Ellipsis:
        self.default = Undefined
    if self.default is not Undefined and self.default_factory is not None:
        raise TypeError(
            "Cannot specify both `default` and `default_factory`."
        )

    # Extract field namespace and ownership
    owner = kwargs_copy.pop('owner', None)
    name = kwargs_copy.pop('name', None)
    alias = kwargs_copy.pop('alias', None)
    slug = kwargs_copy.pop('slug', None)
    title = kwargs_copy.pop('title', None)

    # Set field namespace and ownership
    self.owner = owner if owner is not None else Deferred
    self.name = name if name is not None else Deferred
    self.alias = alias if alias is not None else Deferred
    self.slug = slug if slug is not None else Deferred
    self.title = title if title is not None else Deferred

    # Set field annotation and metadata
    annotation, annotation_metadata = \
        self._extract_metadata(kwargs_copy.pop('annotation', None))
    self.metadata = \
        self._collect_metadata(kwargs_copy)
    self.metadata += annotation_metadata
    self.annotation = \
        eval_type_lenient_deep(annotation, globals(), locals())

    # Set field information
    self.source = kwargs_copy.pop('source', None)
    self.alias_priority = kwargs_copy.pop('alias_priority', None)
    self.description = kwargs_copy.pop('description', None)
    self.examples = kwargs_copy.pop('examples', None)
    self.deprecated = kwargs_copy.pop('deprecated', None)
    self.frozen = kwargs_copy.pop('frozen', None)
    self.repr = kwargs_copy.pop('repr', True)
    self.init = kwargs_copy.pop('init', True)
    self.init_var = kwargs_copy.pop('init_var', None)
    self.kw_only = kwargs_copy.pop('kw_only', None)
    self.validation_alias = kwargs_copy.pop('validation_alias', None)
    self.serialization_alias = kwargs_copy.pop('serialization_alias', None)
    self.exclude = kwargs_copy.pop('exclude', None)
    self.discriminator = kwargs_copy.pop('discriminator', None)
    self.json_schema_extra = kwargs_copy.pop('json_schema_extra', None)
    self.validate_default = kwargs_copy.pop('validate_default', None)
    self.recursive_guard = kwargs_copy.pop('recursive_guard', None)
    self.unique = kwargs_copy.pop('unique', None)
    self.indexed = kwargs_copy.pop('indexed', None)
    self.linked = kwargs_copy.pop('linked', None)
    self.collection = kwargs_copy.pop('collection', None)
    self.target = kwargs_copy.pop('target', None)
    self.target_ref = kwargs_copy.pop('target_ref', None)
    self.target_schemas = kwargs_copy.pop('target_schemas', None)
    self.association = kwargs_copy.pop('association', None)
    self.association_alias = kwargs_copy.pop('association_alias', None)
    self.rel_attribute = kwargs_copy.pop('rel_attribute', None)
    self.rel_backref = kwargs_copy.pop('rel_backref', None)
    self.rel_cascade = kwargs_copy.pop('rel_cascade', None)
    self.rel_load = kwargs_copy.pop('rel_load', None)
    self.rel_extra = kwargs_copy.pop('rel_extra', None)
    self.column_extra = kwargs_copy.pop('column_extra', None)
    self.data_type = kwargs_copy.pop('data_type', None)
    self.data_collation = kwargs_copy.pop('data_collation', None)
    self.data_none_as_null = kwargs_copy.pop('data_none_as_null', None)
    self.data_extra = kwargs_copy.pop('data_extra', None)

    # Check for remaining keyword arguments
    if kwargs_copy:
        raise TypeError(
            f"Unexpected remaining keyword arguments: "
            f"{', '.join(kwargs_copy)}."
        )

    # Initialize field information namespace and ownership
    self._init_field_info_namespace()
    self._init_field_info_ownership_and_association()
    self._init_field_info_target()

    # Finalize field information annotation build
    if self.owner is Deferred:
        return
    if config := get_config(self.owner):
        if config.get('defer_build', False):
            return
    self.build()

get_default

get_default(*, call_default_factory: bool = False) -> Any

Get the default value.

We expose an option for whether to call the default_factory (if present), as calling it may result in side effects that we want to avoid. However, there are times when it really should be called (namely, when instantiating a model via model_construct).

Parameters:

Name Type Description Default
call_default_factory bool

Whether to call the default_factory or not. Defaults to False.

False

Returns:

Type Description
Any

The default value, calling the default factory if requested or None if not set.

Source code in .venv/lib/python3.12/site-packages/pydantic/fields.py
def get_default(self, *, call_default_factory: bool = False) -> Any:
    """Get the default value.

    We expose an option for whether to call the default_factory (if present), as calling it may
    result in side effects that we want to avoid. However, there are times when it really should
    be called (namely, when instantiating a model via `model_construct`).

    Args:
        call_default_factory: Whether to call the default_factory or not. Defaults to `False`.

    Returns:
        The default value, calling the default factory if requested or `None` if not set.
    """
    if self.default_factory is None:
        return _utils.smart_deepcopy(self.default)
    elif call_default_factory:
        return self.default_factory()
    else:
        return None

rebuild_annotation

rebuild_annotation() -> Any

Attempts to rebuild the original annotation for use in function signatures.

If metadata is present, it adds it to the original annotation using Annotated. Otherwise, it returns the original annotation as-is.

Note that because the metadata has been flattened, the original annotation may not be reconstructed exactly as originally provided, e.g. if the original type had unrecognized annotations, or was annotated with a call to pydantic.Field.

Returns:

Type Description
Any

The rebuilt annotation.

Source code in .venv/lib/python3.12/site-packages/pydantic/fields.py
def rebuild_annotation(self) -> Any:
    """Attempts to rebuild the original annotation for use in function signatures.

    If metadata is present, it adds it to the original annotation using
    `Annotated`. Otherwise, it returns the original annotation as-is.

    Note that because the metadata has been flattened, the original annotation
    may not be reconstructed exactly as originally provided, e.g. if the original
    type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.

    Returns:
        The rebuilt annotation.
    """
    if not self.metadata:
        return self.annotation
    else:
        # Annotated arguments must be a tuple
        return typing_extensions.Annotated[(self.annotation, *self.metadata)]  # type: ignore

apply_typevars_map

apply_typevars_map(
    typevars_map: dict[Any, Any] | None,
    types_namespace: dict[str, Any] | None,
) -> None

Apply a typevars_map to the annotation.

This method is used when analyzing parametrized generic types to replace typevars with their concrete types.

This method applies the typevars_map to the annotation in place.

Parameters:

Name Type Description Default
typevars_map dict[Any, Any] | None

A dictionary mapping type variables to their concrete types.

required
types_namespace dict | None

A dictionary containing related types to the annotated type.

required
See Also

pydantic._internal._generics.replace_types is used for replacing the typevars with their concrete types.

Source code in .venv/lib/python3.12/site-packages/pydantic/fields.py
def apply_typevars_map(self, typevars_map: dict[Any, Any] | None, types_namespace: dict[str, Any] | None) -> None:
    """Apply a `typevars_map` to the annotation.

    This method is used when analyzing parametrized generic types to replace typevars with their concrete types.

    This method applies the `typevars_map` to the annotation in place.

    Args:
        typevars_map: A dictionary mapping type variables to their concrete types.
        types_namespace (dict | None): A dictionary containing related types to the annotated type.

    See Also:
        pydantic._internal._generics.replace_types is used for replacing the typevars with
            their concrete types.
    """
    annotation = _typing_extra.eval_type_lenient(self.annotation, types_namespace)
    self.annotation = _generics.replace_types(annotation, typevars_map)

from_annotation classmethod

from_annotation(
    annotation: type[Any],
    *,
    owner: type[Object] | None = Undefined,
    name: str | None = Undefined,
) -> Self

Creates a field info instance from a bare annotation.

Examples:

It is used internally to create a FieldInfo from a bare annotation like this:

>>> from plateforme import BaseModel
... class MyModel(BaseModel):
...     foo: int  # <-- like this

We also account for the case where the annotation can be an instance of Annotated and where one of the (not first) arguments in Annotated is an instance of FieldInfo, e.g.:

>>> import annotated_types
... from typing import Annotated
... from plateforme import BaseModel, Field
>>> class MyModel(BaseModel):
...     foo: Annotated[int, annotated_types.Gt(42)]
...     bar: Annotated[int, Field(gt=42)]

Parameters:

Name Type Description Default
annotation type[Any]

An annotation object.

required
owner type[Object] | None

The owner of the field. Defaults to Undefined.

Undefined
name str | None

The name of the field. Defaults to Undefined.

Undefined

Returns:

Type Description
Self

A new field info instance with the given annotation and metadata.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
@classmethod
def from_annotation(  # type: ignore[override, unused-ignore]
    cls,
    annotation: type[Any],
    *,
    owner: type[Object] | None = Undefined,
    name: str | None = Undefined,
) -> Self:
    """Creates a field info instance from a bare annotation.

    Examples:
        It is used internally to create a `FieldInfo` from a bare
        annotation like this:

        >>> from plateforme import BaseModel
        ... class MyModel(BaseModel):
        ...     foo: int  # <-- like this

        We also account for the case where the annotation can be an
        instance of `Annotated` and where one of the (not first) arguments
        in `Annotated` is an instance of `FieldInfo`, e.g.:

        >>> import annotated_types
        ... from typing import Annotated
        ... from plateforme import BaseModel, Field

        >>> class MyModel(BaseModel):
        ...     foo: Annotated[int, annotated_types.Gt(42)]
        ...     bar: Annotated[int, Field(gt=42)]

    Args:
        annotation: An annotation object.
        owner: The owner of the field. Defaults to ``Undefined``.
        name: The name of the field. Defaults to ``Undefined``.

    Returns:
        A new field info instance with the given annotation and metadata.
    """
    # Check if the annotation is a final variable
    final: bool = Undefined
    if is_finalvar(annotation):
        final = True
        if annotation is not Final:  # type: ignore[comparison-overlap]
            annotation = typing.get_args(annotation)[0]

    # Handle annotated type
    if is_annotated(annotation):
        annotation_type, *extra_args = typing.get_args(annotation)
        if is_finalvar(annotation_type):
            final = True
        annotation_metadata: list[Any] = []
        for arg in extra_args:
            if not isinstance(arg, _FieldInfo):
                annotation_metadata.append(arg)
            else:
                annotation_metadata.extend(arg.metadata)
        field_info = cls.merge_field_infos(
            *[a for a in extra_args if isinstance(a, _FieldInfo)],
            source='from_annotation',
            owner=owner,
            name=name,
            annotation=annotation_type,
            frozen=final,
        )
        field_info.metadata = annotation_metadata
        return field_info

    # Handle standard case
    return cls(
        source='from_annotation',
        owner=owner,
        name=name,
        annotation=annotation,
        frozen=final,
    )

from_annotated_attribute classmethod

from_annotated_attribute(
    annotation: type[Any],
    default: Any,
    *,
    owner: type[Object] | None = Undefined,
    name: str | None = Undefined,
) -> Self

Create a field info instance from an annotation with default value.

Examples:

It is used internally to create a FieldInfo from an annotated attribute like this:

>>> import annotated_types
... from typing import Annotated
... from plateforme import BaseModel, Field
>>> class MyModel(BaseModel):
...     foo: int = 4  # <-- like this
...     baz: int = Field(4, gt=4)  # or this
...     baz: Annotated[int, annotated_types.Gt(4)] = 4  # or this

Parameters:

Name Type Description Default
annotation type[Any]

The type annotation of the field.

required
default Any

The default value of the field.

required
owner type[Object] | None

The owner of the field. Defaults to Undefined.

Undefined
name str | None

The name of the field. Defaults to Undefined.

Undefined

Returns:

Type Description
Self

A new field info instance with the given annotation and default

Self

value.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
@classmethod
def from_annotated_attribute(  # type: ignore[override, unused-ignore]
    cls,
    annotation: type[Any],
    default: Any,
    *,
    owner: type[Object] | None = Undefined,
    name: str | None = Undefined,
) -> Self:
    """Create a field info instance from an annotation with default value.

    Examples:
        It is used internally to create a `FieldInfo` from an annotated
        attribute like this:

        >>> import annotated_types
        ... from typing import Annotated
        ... from plateforme import BaseModel, Field

        >>> class MyModel(BaseModel):
        ...     foo: int = 4  # <-- like this
        ...     baz: int = Field(4, gt=4)  # or this
        ...     baz: Annotated[int, annotated_types.Gt(4)] = 4  # or this

    Args:
        annotation: The type annotation of the field.
        default: The default value of the field.
        owner: The owner of the field. Defaults to ``Undefined``.
        name: The name of the field. Defaults to ``Undefined``.

    Returns:
        A new field info instance with the given annotation and default
        value.
    """
    # Check if the annotation is the same as the default value
    if annotation is default:
        raise PlateformeError(
            f"Error when building FieldInfo from annotated attribute "
            f"{annotation!r} with default value {default!r}. Make sure "
            f"you don't have any field name clashing with a type "
            f"annotation.",
            code='field-invalid-config',
        )

    # Check if the annotation is a final variable
    final: bool = Undefined
    if is_finalvar(annotation):
        final = True
        if annotation is not Final:  # type: ignore[comparison-overlap]
            annotation = typing.get_args(annotation)[0]

    # Handle default value as field info instance
    if isinstance(default, _FieldInfo):
        annotation_type, annotation_metadata = \
            FieldInfo._extract_metadata(annotation)
        field_info = cls.merge_field_infos(
            *[x for x in annotation_metadata if isinstance(x, _FieldInfo)],
            default,
            source='from_annotated_attribute',
            owner=owner,
            name=name,
            annotation=annotation_type,
            frozen=final,
        )
        field_info.metadata += annotation_metadata
        return field_info

    # Handle default value as dataclass field
    elif isinstance(default, dataclasses.Field):
        init_var = False
        if annotation is dataclasses.InitVar:
            init_var = True
            annotation = Any  # type: ignore[assignment]
        elif isinstance(annotation, dataclasses.InitVar):
            init_var = True
            annotation = annotation.type
        annotation_type, annotation_metadata = \
            FieldInfo._extract_metadata(annotation)
        field_info = cls.merge_field_infos(
            *[x for x in annotation_metadata if isinstance(x, _FieldInfo)],
            cls._from_dataclass_field(default),
            source='from_annotated_attribute',
            owner=owner,
            name=name,
            annotation=annotation_type,
            frozen=final,
            init_var=init_var,
        )
        field_info.metadata += annotation_metadata
        return field_info

    # Handle annotated type
    elif is_annotated(annotation):
        annotation_type, *extra_args = typing.get_args(annotation)
        annotation_metadata = []
        for arg in extra_args:
            if not isinstance(arg, _FieldInfo):
                annotation_metadata.append(arg)
            else:
                annotation_metadata.extend(arg.metadata)
        field_info = cls.merge_field_infos(
            *[a for a in extra_args if isinstance(a, _FieldInfo)],
            source='from_annotated_attribute',
            owner=owner,
            name=name,
            annotation=annotation_type,
            default=default,
            frozen=final,
        )
        field_info.metadata = annotation_metadata
        return field_info

    # Handle standard case
    return cls(
        source='from_annotated_attribute',
        owner=owner,
        name=name,
        annotation=annotation,
        default=default,
        frozen=final,
    )

from_field classmethod

from_field(
    default: Any = Undefined,
    **kwargs: Unpack[FieldInfoFromFieldDict],
) -> Self

Create a field info object instance with a field function.

Parameters:

Name Type Description Default
default Any

Since this is replacing the field's default, its first argument is used to set the default, use ellipsis ... to indicate the field is required.

Undefined
**kwargs Unpack[FieldInfoFromFieldDict]

Additional keyword arguments. See the field information configuration dictionary FieldInfoFromFieldDict for more information on the expected keyword arguments.

{}

Raises:

Type Description
TypeError

If annotation, owner, or name is passed as a keyword argument.

Returns:

Type Description
Self

A new field info instance with the given parameters.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
@classmethod
def from_field(  # type: ignore[override, unused-ignore]
    cls, default: Any = Undefined, **kwargs: Unpack[FieldInfoFromFieldDict]
) -> Self:
    """Create a field info object instance with a field function.

    Args:
        default: Since this is replacing the field's default, its first
            argument is used to set the default, use ellipsis ``...`` to
            indicate the field is required.
        **kwargs: Additional keyword arguments. See the field information
            configuration dictionary `FieldInfoFromFieldDict` for more
            information on the expected keyword arguments.

    Raises:
        TypeError: If `annotation`, `owner`, or `name` is passed as a
            keyword argument.

    Returns:
        A new field info instance with the given parameters.
    """
    # Check keyword arguments
    for key in ('owner', 'name', 'annotation'):
        if key in kwargs:
            raise TypeError(
                f"The keyword argument {key!r} is not permitted for a "
                f"field function keyword argument."
            )
    # Create field info instance
    return cls(source='from_field', default=default, **kwargs)

from_field_info classmethod

from_field_info(
    base: FieldInfo, **overrides: Unpack[FieldInfoDict[Any]]
) -> Self

Create a field info object instance from a base field info.

It constructs a new field info instance from a base field info instance with additional keyword arguments to override the base field info attributes.

Parameters:

Name Type Description Default
base FieldInfo

The base field info to create the field info instance from.

required
**overrides Unpack[FieldInfoDict[Any]]

Additional keyword arguments to override the base field info attributes. See the field information configuration dictionary FieldInfoDict for more information on the expected keyword arguments.

{}

Returns:

Type Description
Self

A new field info instance with the given parameters.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
@classmethod
def from_field_info(
    cls, base: _FieldInfo, **overrides: Unpack[FieldInfoDict[Any]]
) -> Self:
    """Create a field info object instance from a base field info.

    It constructs a new field info instance from a base field info instance
    with additional keyword arguments to override the base field info
    attributes.

    Args:
        base: The base field info to create the field info instance from.
        **overrides: Additional keyword arguments to override the base
            field info attributes. See the field information configuration
            dictionary `FieldInfoDict` for more information on the expected
            keyword arguments.

    Returns:
        A new field info instance with the given parameters.
    """
    # Clean up override arguments
    overrides = {  # type: ignore[assignment]
        k: v for k, v in overrides.items() if v is not Undefined
    }

    # Retrieve keyword arguments and metadata from base field info
    kwargs: dict[str, Any] = base._attributes_set
    metadata = {}
    for constraint in base.metadata:
        if not isinstance(constraint, _FieldInfo):
            metadata[type(constraint)] = constraint
    kwargs.update(overrides)
    kwargs.setdefault('source', 'from_field_info')

    # Create field info instance
    field_info = cls(**kwargs)
    field_info.metadata += list(metadata.values())
    return field_info

merge_field_infos classmethod

merge_field_infos(
    *field_infos: FieldInfo,
    **overrides: Unpack[FieldInfoDict[Any]],
) -> Self

Merge field info instances keeping only explicitly set attributes.

It merges multiple FieldInfo instances into a single one, keeping only the attributes that are explicitly set in each instance. The later FieldInfo instances override the earlier ones, while the overrides keyword arguments are applied to the merged FieldInfo instance.

FIXME: When multiple field info instances are merged, Pydantic uses its own FieldInfo class to merge them. This is not ideal as it does not take into account the FieldInfo class hierarchy. This impacts typically fields with annotation that uses the Field functions.

Parameters:

Name Type Description Default
*field_infos FieldInfo

The field info instances to merge.

()
**overrides Unpack[FieldInfoDict[Any]]

Additional keyword arguments to override the merged field info attributes. See the field information configuration dictionary FieldInfoDict for more information on the expected keyword arguments.

{}

Returns:

Type Description
Self

A new field info instance with the merged attributes.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
@classmethod
def merge_field_infos(  # type: ignore[override, unused-ignore]
    cls, *field_infos: _FieldInfo, **overrides: Unpack[FieldInfoDict[Any]]
) -> Self:
    """Merge field info instances keeping only explicitly set attributes.

    It merges multiple `FieldInfo` instances into a single one, keeping
    only the attributes that are explicitly set in each instance. The later
    `FieldInfo` instances override the earlier ones, while the `overrides`
    keyword arguments are applied to the merged `FieldInfo` instance.

    FIXME: When multiple field info instances are merged, Pydantic uses its
    own `FieldInfo` class to merge them. This is not ideal as it does not
    take into account the `FieldInfo` class hierarchy. This impacts
    typically fields with annotation that uses the `Field` functions.

    Args:
        *field_infos: The field info instances to merge.
        **overrides: Additional keyword arguments to override the merged
            field info attributes. See the field information configuration
            dictionary `FieldInfoDict` for more information on the expected
            keyword arguments.

    Returns:
        A new field info instance with the merged attributes.
    """
    # Flatten field infos
    flattened_field_infos: list[_FieldInfo] = []
    for field_info in field_infos:
        flattened_field_infos.extend(
            x for x in field_info.metadata if isinstance(x, _FieldInfo)
        )
        flattened_field_infos.append(field_info)
    field_infos = tuple(flattened_field_infos)

    # Retrieve the field info consructor class. If there are multiple field
    # info instances, use the last one that is a subclass of this class. If
    # there are no subclasses, use this class.
    field_info_cls = cls
    for field_info in field_infos:
        if isinstance(field_info, cls):
            field_info_cls = type(field_info)

    # Check if there is only one field info instance to merge and apply
    # the overrides if necessary.
    if len(field_infos) == 1:
        return field_info_cls.from_field_info(field_infos[0], **overrides)

    # Clean up override arguments
    overrides = {  # type: ignore[assignment]
        k: v for k, v in overrides.items() if v is not Undefined
    }

    # Retrieve keyword arguments and metadata from field infos
    kwargs: dict[str, Any] = {}
    metadata = {}
    for field_info in field_infos:
        kwargs.update(field_info._attributes_set)
        for constraint in field_info.metadata:
            if not isinstance(constraint, _FieldInfo):
                metadata[type(constraint)] = constraint
    kwargs.update(overrides)

    # Create field info instance
    field_info = field_info_cls(**kwargs)
    field_info.metadata = list(metadata.values())
    return field_info

build

build(
    *, force: bool = False, raise_errors: bool = True
) -> bool | None

Build the field information target and annotation.

Parameters:

Name Type Description Default
force bool

Whether to force the field information building even if it is already complete. Defaults to False.

False
raise_errors bool

Whether to raise errors if the field information cannot be built. Defaults to True.

True

Returns:

Type Description
bool | None

True if the field information is successfully built, False

bool | None

if the field information cannot be built, and None if the field

bool | None

information is already complete.

Raises:

Type Description
PlateformeError

If the target is not a valid resource or if the target schema is not found in the target resource.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def build(
    self,
    *,
    force: bool = False,
    raise_errors: bool = True,
) -> bool | None:
    """Build the field information target and annotation.

    Args:
        force: Whether to force the field information building even if it
            is already complete. Defaults to ``False``.
        raise_errors: Whether to raise errors if the field information
            cannot be built. Defaults to ``True``.

    Returns:
        ``True`` if the field information is successfully built, ``False``
        if the field information cannot be built, and ``None`` if the field
        information is already complete.

    Raises:
        PlateformeError: If the target is not a valid resource or if the
            target schema is not found in the target resource.
    """
    # Check if field information is already complete
    if self._complete and not force:
        return None
    elif self.target is None:
        self._complete = True
        return True
    else:
        self._complete = False

    # Validate target resource
    if isinstance(self.target, str):
        if not raise_errors:
            return False
        raise PlateformeError(
            f"Cannot build field information for field {self.name!r} of "
            f"resource {self.owner.__qualname__!r}. The target must be a "
            f"valid resource. Got: {self.target!r}.",
            code='field-invalid-config',
        )

    # Update target annotation
    if target_annotation := self.build_target_annotation():
        target_type, *target_metadata = target_annotation

        def ann_test(ann: Any) -> bool:
            assert isinstance(self.target, type)
            if is_forwardref(ann):
                return True
            if isinstance(ann, type) and issubclass(ann, self.target):
                return True
            return False

        def ann_resolver(_: Any) -> Any:
            if target_metadata:
                return Annotated[target_type, *target_metadata]
            return target_type

        if ann_test(self.annotation):
            self.metadata += target_metadata
            self.annotation = target_type
        else:
            try:
                annotation = Annotation.replace(
                    self.annotation,
                    test=ann_test,
                    resolver=ann_resolver,
                )
            except PlateformeError as error:
                if raise_errors:
                    raise error
                return False

            self.annotation = annotation

    # Update recursive guard
    if recursive_guard := self.build_recursive_guard():
        self.recursive_guard = recursive_guard

    self._complete = True

    return True

build_recursive_guard

build_recursive_guard() -> str | None

Build the field information recursive guard.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def build_recursive_guard(self) -> str | None:
    """Build the field information recursive guard."""
    # Check if recursive guard is already set
    if self.recursive_guard is not None:
        return self.recursive_guard

    # Try to infer recursive guard from owner resource
    if is_model(self.owner):
        resource = self.owner.__pydantic_resource__
        if resource is None:
            return None
    elif is_resource(self.owner):
        resource = self.owner
    else:
        return None

    resource_field = resource.resource_fields.get(self.name, None)
    if resource_field is None:
        return None
    return resource_field.association_alias

build_target_annotation

build_target_annotation() -> tuple[Any, ...] | None

Build the field information target annotation and metadata.

For fields that are linked to another resource, this method returns either a tuple containing the target type itself or a selector reference to the target type, or a tuple containing the target schema model with optional selector reference annotation when target_schemas and target_ref are both set.

Returns:

Type Description
tuple[Any, ...] | None

A tuple containing the field information target annotation and

tuple[Any, ...] | None

metadata, or None if the field is not linked.

Raises:

Type Description
PlateformeError

If no resource schema models matches the specified target schema models of the field information.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def build_target_annotation(self) -> tuple[Any, ...] | None:
    """Build the field information target annotation and metadata.

    For fields that are linked to another resource, this method returns
    either a tuple containing the target type itself or a selector
    reference to the target type, or a tuple containing the target schema
    model with optional selector reference annotation when `target_schemas`
    and `target_ref` are both set.

    Returns:
        A tuple containing the field information target annotation and
        metadata, or ``None`` if the field is not linked.

    Raises:
        PlateformeError: If no resource schema models matches the specified
            target schema models of the field information.
    """
    from ..selectors import Key

    # Skip if target is not a resource
    if self.target is None or isinstance(self.target, str):
        return None

    if not self.target_ref and not self.target_schemas:
        return (self.target,)

    # Retrieve target schema model
    target_model = None
    if self.target_schemas is True:
        self.target_schemas = ('model',)
    if self.target_schemas:
        for target_schema in self.target_schemas:
            if schema := self.target.resource_schemas.get(target_schema):
                target_model = schema
                break
        if target_model is None:
            raise PlateformeError(
                f"Cannot resolve target schema for field {self.name!r} "
                f"of {self.owner.__qualname__!r}. "
                f"Got: {self.target_schemas!r}.",
                code='field-invalid-config',
            )

    # Return target annotation and metadata
    if self.target_ref and self.target_schemas:
        return (target_model, Key.create(self.target))
    elif self.target_ref:
        return (Key.create(self.target),)
    else:
        return (target_model,)

create_column

create_column() -> Column[Any]

Create a SQLAlchemy column object from the field information.

Raises:

Type Description
TypeError

If the field is linked.

ValueError

If the owner is not a valid resource.

PlateformeError

If the field annotation or data type engine is invalid.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def create_column(self) -> Column[Any]:
    """Create a SQLAlchemy column object from the field information.

    Raises:
        TypeError: If the field is linked.
        ValueError: If the owner is not a valid resource.
        PlateformeError: If the field annotation or data type engine is
            invalid.
    """
    # Validate field information
    if not is_resource(self.owner):
        raise ValueError(
            f"Cannot create a column for field {self.name!r} of "
            f"{self.owner.__qualname__!r}. The owner must be a valid "
            f"resource.",
        )
    if self.linked:
        raise TypeError(
            f"Cannot create a column for linked field {self.name!r} of "
            f"{self.owner.__qualname__!r}. Linked fields are not "
            f"supported by the `create_column` method.",
        )

    # Resolve data type engine from annotation
    try:
        if self.data_type is not None:
            type_engine = self.data_type
        else:
            type_engine = resolve_data_type_engine(
                self.annotation,
                self.owner.resource_config.arbitrary_types_allowed,
                **{
                    k: v for k, v in self._attributes_set.items()
                    if k.startswith('data_')
                },
            )
    except TypeError as error:
        raise PlateformeError(
            f"Field {self.name!r} of resource {self.owner.__qualname__!r} "
            f"has an invalid annotation {self.annotation!r}.",
            code='field-invalid-config',
        ) from error

    # Instantiate data type engine if necessary
    if isinstance(type_engine, type):
        type_engine = type_engine()

    # Validate data type engine
    if not isinstance(type_engine, BaseTypeEngine):
        raise PlateformeError(
            f"Field {self.name!r} of resource {self.owner.__qualname__!r} "
            f"has an invalid data type engine {type_engine!r}.",
            code='field-invalid-config',
        )

    return Column(
        name=self.name,
        type_=type_engine,
        index=self.indexed or False,
        unique=self.unique or False,
        nullable=self.is_nullable(),
        **(self.column_extra or {}),
    )

entries

entries(
    *, scope: Literal["all", "set"] = "all"
) -> dict[str, Any]

Return the field information entries based on the specified scope.

Parameters:

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

The scope of the field information dictionary to return. It can be either 'all' to return all entries, or 'set' to return only the field information entries that have been explicitly set. Defaults to 'all'.

'all'

Returns:

Type Description
dict[str, Any]

A dictionary containing the field information entries based on the

dict[str, Any]

specified scope.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def entries(
    self, *, scope: Literal['all', 'set'] = 'all'
) -> dict[str, Any]:
    """Return the field information entries based on the specified scope.

    Args:
        scope: The scope of the field information dictionary to return. It
            can be either ``'all'`` to return all entries, or ``'set'`` to
            return only the field information entries that have been
            explicitly set. Defaults to ``'all'``.

    Returns:
        A dictionary containing the field information entries based on the
        specified scope.
    """
    if scope == 'set':
        return self._attributes_set
    return {
        key: getattr(self, key)
        for key in self.__attributes__ if not key.startswith('_')
    }

is_cascading

is_cascading(*options: CascadeRule) -> bool | None

Check if the field association cascades the provided options.

It defines whether or not to cascade operations to the field associated target resource. This determines if operations on the field owner resource should extend to its target resource. It is used to infer if it is possible to simultaneously create, read, update, upsert, or delete associated target resource through the same endpoint, effectively treating the associated target data as part of the owner resource's data model.

Parameters:

Name Type Description Default
*options CascadeRule

The cascade rules to check against. The possible options are 'delete', 'delete-orphan', 'expunge', 'merge', 'refresh-expire', 'save-update', and all, where the latter is a shorthand for 'save-update, merge, refresh-expire, expunge, delete', and is often used as in 'all, delete-orphan' to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated.

Those can be set using the rel_cascade field information attribute. If not set, it resolves with the following options: - 'save-update, merge' when the association is bidirectional, - 'delete, delete-orphan' when the target resource link is identifying, - 'refresh-expire, expunge' when the target resource link is indexing.

()

Returns:

Type Description
bool | None

Whether the field association cascades the provided options, or

bool | None

None if the field is not linked.

Raises:

Type Description
ValueError

If the field rel_cascade corresponding resource relationship property is not defined.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def is_cascading(self, *options: CascadeRule) -> bool | None:
    """Check if the field association cascades the provided options.

    It defines whether or not to cascade operations to the field associated
    target resource. This determines if operations on the field owner
    resource should extend to its target resource. It is used to infer if
    it is possible to simultaneously create, read, update, upsert, or
    delete associated target resource through the same endpoint,
    effectively treating the associated target data as part of the owner
    resource's data model.

    Args:
        *options: The cascade rules to check against. The possible
            options are ``'delete'``, ``'delete-orphan'``, ``'expunge'``,
            ``'merge'``, ``'refresh-expire'``, ``'save-update'``, and
            ``all``, where the latter is a shorthand for
            ``'save-update, merge, refresh-expire, expunge, delete'``, and
            is often used as in ``'all, delete-orphan'`` to indicate that
            related objects should follow along with the parent object in
            all cases, and be deleted when de-associated.

            Those can be set using the `rel_cascade` field information
            attribute. If not set, it resolves with the following options:
            - ``'save-update, merge'`` when the association is
                bidirectional,
            - ``'delete, delete-orphan'`` when the target resource link is
                identifying,
            - ``'refresh-expire, expunge'`` when the target resource link is
                indexing.

    Returns:
        Whether the field association cascades the provided options, or
        ``None`` if the field is not linked.

    Raises:
        ValueError: If the field `rel_cascade` corresponding resource
            relationship property is not defined.
    """
    if is_model(self.owner):
        resource = self.owner.__pydantic_resource__
    elif is_resource(self.owner):
        resource = self.owner

    if resource is None or not self.linked:
        return None

    rel_attr = resource.resource_attributes.get(self.name, None)
    if rel_attr is None:
        raise ValueError(
            f"Cannot determine if the field {self.name!r} of "
            f"{resource.__qualname__!r} is cascading. The corresponding "
            f"resource relationship property is not yet defined.",
        )
    rel_prop = rel_attr.property
    assert isinstance(rel_prop, RelationshipProperty)

    options_set = set(options)
    if 'all' in options_set:
        options_set.remove('all')
        options_set.update({
            'delete',
            'expunge',
            'merge',
            'refresh-expire',
            'save-update',
        })

    for option in options_set:
        match option:
            case 'delete':
                if not rel_prop.cascade.delete:
                    return False
            case 'delete-orphan':
                if not rel_prop.cascade.delete_orphan:
                    return False
            case 'expunge':
                if not rel_prop.cascade.expunge:
                    return False
            case 'merge':
                if not rel_prop.cascade.merge:
                    return False
            case 'refresh-expire':
                if not rel_prop.cascade.refresh_expire:
                    return False
            case 'save-update':
                if not rel_prop.cascade.save_update:
                    return False
            case _:
                raise NotImplementedError(
                    f"Unsupported option: {option!r}."
                )

    return True

is_eagerly

is_eagerly() -> bool | None

Check if the field association loading is eager.

It defines whether or not to load eagerly the field associated target resource data when loading the field owner resource. It is used in resource schemas and endpoints to infer if the target resource data should be returned and traversed along with the owner resource data.

Returns:

Type Description
bool | None

Whether the field association loading is eager, or None if the

bool | None

field is not linked.

Raises:

Type Description
ValueError

If the field rel_load corresponding resource relationship property is not defined.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def is_eagerly(self) -> bool | None:
    """Check if the field association loading is eager.

    It defines whether or not to load eagerly the field associated target
    resource data when loading the field owner resource. It is used in
    resource schemas and endpoints to infer if the target resource data
    should be returned and traversed along with the owner resource data.

    Returns:
        Whether the field association loading is eager, or ``None`` if the
        field is not linked.

    Raises:
        ValueError: If the field `rel_load` corresponding resource
            relationship property is not defined.
    """
    if is_model(self.owner):
        resource = self.owner.__pydantic_resource__
    elif is_resource(self.owner):
        resource = self.owner

    if resource is None or not self.linked:
        return None

    rel_attr = resource.resource_attributes.get(self.name, None)
    if rel_attr is None:
        raise ValueError(
            f"Cannot determine if the field {self.name!r} of "
            f"{resource.__qualname__!r} is eagerly loaded. The "
            f"corresponding resource relationship property is not yet "
            f"defined.",
        )
    rel_prop = rel_attr.property
    assert isinstance(rel_prop, RelationshipProperty)

    return rel_prop.lazy in ('joined', 'selectin')

is_identifying

is_identifying() -> bool | None

Check if the field exists within its owner identifiers.

The field is considered identifying if either the field unique attribute is set to True, or if the field alias is found within a composite identifier of its owner resource.

Returns:

Type Description
bool | None

Whether the field is identifying its owner, or None if the

bool | None

field is not attached to a resource.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def is_identifying(self) -> bool | None:
    """Check if the field exists within its owner identifiers.

    The field is considered identifying if either the field `unique`
    attribute is set to ``True``, or if the field `alias` is found within a
    composite identifier of its owner resource.

    Returns:
        Whether the field is identifying its owner, or ``None`` if the
        field is not attached to a resource.
    """
    if self.unique:
        return True

    if is_model(self.owner):
        resource = self.owner.__pydantic_resource__
        if resource is None:
            return None
    elif is_resource(self.owner):
        resource = self.owner
    else:
        return None

    return any(
        self.alias in identifier
        for identifier in resource.resource_identifiers
    )

is_indexing

is_indexing() -> bool | None

Check if the field exists within its owner indexes.

The field is considered indexing if either the field indexed or unique attribute is set to True, or if the field alias is found within a composite index of its owner resource.

Returns:

Type Description
bool | None

Whether the field is indexing its owner, or None if the field

bool | None

is not attached to a resource.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def is_indexing(self) -> bool | None:
    """Check if the field exists within its owner indexes.

    The field is considered indexing if either the field `indexed` or
    `unique` attribute is set to ``True``, or if the field `alias` is found
    within a composite index of its owner resource.

    Returns:
        Whether the field is indexing its owner, or ``None`` if the field
        is not attached to a resource.
    """
    if self.indexed:
        return True

    if is_model(self.owner):
        resource = self.owner.__pydantic_resource__
        if resource is None:
            return None
    elif is_resource(self.owner):
        resource = self.owner
    else:
        return None

    return any(
        self.alias in index
        for index in resource.resource_indexes
    )

is_nullable

is_nullable() -> bool

Check if the field is nullable.

It is considered nullable if the field accepts None as a value.

Returns:

Type Description
bool

Whether the field is nullable.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def is_nullable(self) -> bool:
    """Check if the field is nullable.

    It is considered nullable if the field accepts ``None`` as a value.

    Returns:
        Whether the field is nullable.
    """
    return self.annotation is NoneType or is_optional(self.annotation)

is_required

is_required() -> bool

Check if the field is required.

It is considered required if it does not have a default value, i.e. it is not set to Undefined and does not have a default factory.

Returns:

Type Description
bool

Whether the field is required.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def is_required(self) -> bool:
    """Check if the field is required.

    It is considered required if it does not have a default value, i.e. it
    is not set to ``Undefined`` and does not have a default factory.

    Returns:
        Whether the field is required.
    """
    if self.default is Undefined and self.default_factory is None:
        return True
    return super().is_required()

ComputedFieldInfo dataclass

ComputedFieldInfo(
    *,
    wrapped_property: property,
    return_type: Any,
    alias: str,
    alias_priority: int | None,
    title: str,
    description: str | None,
    examples: list[Any] | None,
    json_schema_extra: JsonSchemaDict
    | Callable[[JsonSchemaDict], None]
    | None,
    repr: bool,
    name: str,
    slug: str,
    deprecated: Deprecated | str | bool | None,
)

Bases: ComputedFieldInfo

A computed field information.

A container for data from @computed_field so it can access while building the pydantic-core schema.

Attributes:

Name Type Description
decorator_repr str

A class variable representing the decorator string @computed_field.

wrapped_property property

The wrapped computed field property.

name str

The name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. When created from the decorator @computed_field, it is inferred from the wrapped property name snake cased.

return_type Any

An optional return type for serialization logic to expect when serializing to JSON. If included, this must be correct, otherwise a TypeError is raised. If no return type is specified Any is used, which does runtime introspection to handle arbitrary objects.

alias str

The alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. When created from the decorator @computed_field, it is inferred from the wrapped property identifier snake cased. It is used when serializing the computed field if by_alias=True.

alias_priority int | None

The priority of the field's alias. This affects whether an alias generator is used or not. Defaults to None.

slug str

The slug name of the field. It must adhere to a specific SLUG pattern as defined in the framework's regular expressions repository. When created from the decorator @computed_field, it is inferred from the wrapped property identifier kebab cased.

title str

The human-readable name of the field. It must adhere to a specific TITLE pattern as defined in the framework's regular expressions repository. When created from the decorator @computed_field, it is inferred from the wrapped property identifier titleized.

description str | None

The description of the field. Defaults to None and uses the function's docstring if available.

examples list[Any] | None

List of examples of the field. Defaults to None.

deprecated Deprecated | str | bool | None

A deprecation message, an instance of Deprecated, or a boolean. If True, a default deprecation message will be emitted when accessing the field. Defaults to None.

repr bool

Whether or not to include the field in the representation. Defaults to False for private properties and True for public properties.

json_schema_extra JsonSchemaDict | Callable[[JsonSchemaDict], None] | None

Dictionary or callable to provide extra JSON schema properties. Defaults to None.

PrivateAttr

PrivateAttr(
    default: Any = PydanticUndefined,
    *,
    default_factory: Callable[[], Any] | None = None,
) -> Any

Usage docs: https://docs.pydantic.dev/2.6/concepts/models/#private-model-attributes

Indicates that an attribute is intended for private use and not handled during normal validation/serialization.

Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner.

Private attributes are stored in __private_attributes__ on the model.

Parameters:

Name Type Description Default
default Any

The attribute's default value. Defaults to Undefined.

PydanticUndefined
default_factory Callable[[], Any] | None

Callable that will be called when a default value is needed for this attribute. If both default and default_factory are set, an error will be raised.

None

Returns:

Type Description
Any

An instance of ModelPrivateAttr class.

Raises:

Type Description
ValueError

If both default and default_factory are set.

Source code in .venv/lib/python3.12/site-packages/pydantic/fields.py
def PrivateAttr(
    default: Any = PydanticUndefined,
    *,
    default_factory: typing.Callable[[], Any] | None = None,
) -> Any:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/models/#private-model-attributes

    Indicates that an attribute is intended for private use and not handled during normal validation/serialization.

    Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner.

    Private attributes are stored in `__private_attributes__` on the model.

    Args:
        default: The attribute's default value. Defaults to Undefined.
        default_factory: Callable that will be
            called when a default value is needed for this attribute.
            If both `default` and `default_factory` are set, an error will be raised.

    Returns:
        An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class.

    Raises:
        ValueError: If both `default` and `default_factory` are set.
    """
    if default is not PydanticUndefined and default_factory is not None:
        raise TypeError('cannot specify both default and default_factory')

    return ModelPrivateAttr(
        default,
        default_factory=default_factory,
    )

ConfigField

ConfigField(
    default: Any = Undefined,
    **kwargs: Unpack[FieldInfoFromConfigDict],
) -> Any

Create a field information instance for a configuration field.

Used to provide extra information about a configuration field for a configuration wrapper.

Parameters:

Name Type Description Default
default Any

Since this is replacing the field's default, its first argument is used to set the default, use ellipsis ... to indicate the field is required.

Undefined
**kwargs Unpack[FieldInfoFromConfigDict]

Additional keyword arguments. See the field information configuration dictionary FieldInfoFromConfigDict for more information on the expected keyword arguments.

{}
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def ConfigField(
    default: Any = Undefined, **kwargs: Unpack[FieldInfoFromConfigDict]
) -> Any:
    """Create a field information instance for a configuration field.

    Used to provide extra information about a configuration field for a
    configuration wrapper.

    Args:
        default: Since this is replacing the field's default, its first
            argument is used to set the default, use ellipsis ``...`` to
            indicate the field is required.
        **kwargs: Additional keyword arguments. See the field information
            configuration dictionary `FieldInfoFromConfigDict` for more
            information on the expected keyword arguments.
    """
    return FieldInfo.from_field(default=default, **kwargs)

Field

Field(
    default: Any = Undefined,
    **kwargs: Unpack[FieldInfoFromFieldDict],
) -> Any

Create a field information instance for a model or resource field.

Used to provide extra information about a field, either for the model or resource schema, or complex validation. Some arguments apply only to number fields (int, float, Decimal) and some apply only to str.

Parameters:

Name Type Description Default
default Any

Since this is replacing the field's default, its first argument is used to set the default, use ellipsis ... to indicate the field is required.

Undefined
**kwargs Unpack[FieldInfoFromFieldDict]

Additional keyword arguments. See the field information configuration dictionary FieldInfoFromFieldDict for more information on the expected keyword arguments.

{}
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def Field(
    default: Any = Undefined, **kwargs: Unpack[FieldInfoFromFieldDict]
) -> Any:
    """Create a field information instance for a model or resource field.

    Used to provide extra information about a field, either for the model or
    resource schema, or complex validation. Some arguments apply only to number
    fields (`int`, `float`, `Decimal`) and some apply only to `str`.

    Args:
        default: Since this is replacing the field's default, its first
            argument is used to set the default, use ellipsis ``...`` to
            indicate the field is required.
        **kwargs: Additional keyword arguments. See the field information
            configuration dictionary `FieldInfoFromFieldDict` for more
            information on the expected keyword arguments.
    """
    return FieldInfo.from_field(default=default, **kwargs)

computed_field

computed_field(__func: _TProperty) -> _TProperty
computed_field(
    *,
    return_type: Any = Undefined,
    alias: str | None = None,
    alias_priority: int | None = None,
    slug: str | None = None,
    title: str | None = None,
    description: str | None = None,
    examples: list[Any] | None = None,
    deprecated: Deprecated | str | bool | None = None,
    repr: bool = True,
    json_schema_extra: JsonSchemaDict
    | Callable[[JsonSchemaDict], None]
    | None = None,
) -> Callable[[_TProperty], _TProperty]
computed_field(
    __func: _TProperty | None = None,
    *,
    return_type: Any = Undefined,
    alias: str | None = None,
    alias_priority: int | None = None,
    slug: str | None = None,
    title: str | None = None,
    description: str | None = None,
    examples: list[Any] | None = None,
    deprecated: Deprecated | str | bool | None = None,
    repr: bool | None = None,
    json_schema_extra: JsonSchemaDict
    | Callable[[JsonSchemaDict], None]
    | None = None,
) -> _TProperty | Callable[[_TProperty], _TProperty]

A decorator for computed fields.

It is used to include property and cached_property when serializing models or dataclasses. This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.

Parameters:

Name Type Description Default
__func _TProperty | None

The property function to wrap. Defaults to None.

None
return_type Any

An optional return type for serialization logic to expect when serializing to JSON. If included, this must be correct, otherwise a TypeError is raised. If no return type is specified Any is used, which does runtime introspection to handle arbitrary objects.

Undefined
alias str | None

The alias name of the field. It must adhere to a specific ALIAS pattern as defined in the framework's regular expressions repository. It is used when serializing the computed field if by_alias=True. Defaults to None.

None
alias_priority int | None

The priority of the field's alias. This affects whether an alias generator is used or not. Defaults to None.

None
slug str | None

The slug name of the field. It must adhere to a specific SLUG pattern as defined in the framework's regular expressions repository. Defaults to None.

None
title str | None

The human-readable name of the field. It must adhere to a specific TITLE pattern as defined in the framework's regular expressions repository. Defaults to None.

None
description str | None

The description of the field. Defaults to None and uses the function's docstring if available.

None
examples list[Any] | None

List of examples of the field. Defaults to None.

None
deprecated Deprecated | str | bool | None

A deprecation message, an instance of Deprecated, or a boolean. If True, a default deprecation message will be emitted when accessing the field. Defaults to None.

None
repr bool | None

Whether or not to include the field in the representation. Defaults to False for private properties and True for public properties.

None
json_schema_extra JsonSchemaDict | Callable[[JsonSchemaDict], None] | None

Dictionary or callable to provide extra JSON schema properties. Defaults to None.

None

Returns:

Type Description
_TProperty | Callable[[_TProperty], _TProperty]

A proxy wrapper for the property.

Raises:

Type Description
PlateformeError

At least one identifier must be either inferred from the function name or provided as an argument. If none are provided, an error iis raised. The identifier is used to generate the field's name, alias, title, and slug. Eacb must adhere to specific regular expression patterns defined in the framework's regular expressions repository.

Examples:

>>> from plateforme import BaseModel, computed_field
>>> class Rectangle(BaseModel):
...     width: int
...     length: int
...
...     @computed_field
...     @property
...     def area(self) -> int:
...         return self.width * self.length
>>> print(Rectangle(width=3, length=2).model_dump())
{'width': 3, 'length': 2, 'area': 6}

If applied to functions not yet decorated with @property or @cached_property, the function is automatically wrapped with property. Although this is more concise, you will lose intellisense in your IDE, and confuse static type checkers, thus explicit use of @property is recommended.

>>> from plateforme import BaseModel, computed_field
>>> class Square(BaseModel):
...    width: float
...
...    # converted to a "property" by "computed_field"
...    @computed_field
...    def area(self) -> float:
...        return round(self.width**2, 2)
...
...   @area.setter
...   def area(self, new_area: float) -> None:
...       self.width = new_area**0.5
...
...   @computed_field(alias='the magic number', repr=False)
...   def random_number(self) -> int:
...       return random.randint(0, 1000)
>>> square = Square(width=1.3)
... print(repr(square))
Square(width=1.3, area=1.69)
>>> print(square.random_number)
3
>>> square.area = 4
... print(square.model_dump_json(by_alias=True))
{"width": 2.0, "area": 4.0, "the magic number": 3}

It is not possible to override a field from a parent class with a computed_field in the child class. MyPy complains about this behavior if allowed, and dataclasses doesn't allow this pattern either as shown in the example below:

>>> from plateforme import BaseModel, computed_field
>>> class Parent(BaseModel):
...     a: str
>>> try:
...     class Child(Parent):
...         @computed_field
...         @property
...         def a(self) -> str:
...             return 'new a'
... except ValueError as e:
...     print(repr(e))
ValueError('you can't override a field with a computed field')

The private properties decorated with @computed_field have their representation set to false repr=False by default:

>>> from functools import cached_property
>>> from plateforme import BaseModel, computed_field
>>> class Model(BaseModel):
...     foo: int
...
...     @computed_field
...     @cached_property
...     def _private_cached_property(self) -> int:
...         return -self.foo
...
...     @computed_field
...     @property
...     def _private_property(self) -> int:
...         return -self.foo
>>> model = Model(foo=1)
... print(repr(model))
Model(foo=1)
Note

Using MyPy, even with the @property or @cached_property applied to your function before @computed_field, it may throw a "Decorated property not supported" error. See https://github.com/python/mypy/issues/1362

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/fields.py
def computed_field(
    __func: _TProperty | None = None,
    *,
    return_type: Any = Undefined,
    alias: str | None = None,
    alias_priority: int | None = None,
    slug: str | None = None,
    title: str | None = None,
    description: str | None = None,
    examples: list[Any] | None = None,
    deprecated: Deprecated | str | bool | None = None,
    repr: bool | None = None,
    json_schema_extra: JsonSchemaDict \
        | typing.Callable[[JsonSchemaDict], None] | None = None,
) -> _TProperty | Callable[[_TProperty], _TProperty]:
    """A decorator for computed fields.

    It is used to include `property` and `cached_property` when serializing
    models or dataclasses. This is useful for fields that are computed from
    other fields, or for fields that are expensive to compute and should be
    cached.

    Args:
        __func: The property function to wrap. Defaults to ``None``.
        return_type: An optional return type for serialization logic to expect
            when serializing to JSON. If included, this must be correct,
            otherwise a ``TypeError`` is raised. If no return type is specified
            ``Any`` is used, which does runtime introspection to handle
            arbitrary objects.
        alias: The alias name of the field. It must adhere to a specific
            ``ALIAS`` pattern as defined in the framework's regular expressions
            repository. It is used when serializing the computed field if
            ``by_alias=True``. Defaults to ``None``.
        alias_priority: The priority of the field's alias. This affects whether
            an alias generator is used or not. Defaults to ``None``.
        slug: The slug name of the field. It must adhere to a specific ``SLUG``
            pattern as defined in the framework's regular expressions
            repository. Defaults to ``None``.
        title: The human-readable name of the field. It must adhere to a
            specific ``TITLE`` pattern as defined in the framework's regular
            expressions repository. Defaults to ``None``.
        description: The description of the field. Defaults to ``None`` and
            uses the function's docstring if available.
        examples: List of examples of the field. Defaults to ``None``.
        deprecated: A deprecation message, an instance of `Deprecated`, or a
            boolean. If ``True``, a default deprecation message will be emitted
            when accessing the field. Defaults to ``None``.
        repr: Whether or not to include the field in the representation.
            Defaults to ``False`` for private properties and ``True`` for
            public properties.
        json_schema_extra: Dictionary or callable to provide extra JSON schema
            properties. Defaults to ``None``.

    Returns:
        A proxy wrapper for the property.

    Raises:
        PlateformeError: At least one identifier must be either inferred from
            the function name or provided as an argument. If none are provided,
            an error iis raised. The identifier is used to generate the field's
            ``name``, ``alias``, ``title``, and ``slug``. Eacb must adhere to
            specific regular expression patterns defined in the framework's
            regular expressions repository.

    Examples:
        >>> from plateforme import BaseModel, computed_field
        >>> class Rectangle(BaseModel):
        ...     width: int
        ...     length: int
        ...
        ...     @computed_field
        ...     @property
        ...     def area(self) -> int:
        ...         return self.width * self.length

        >>> print(Rectangle(width=3, length=2).model_dump())
        {'width': 3, 'length': 2, 'area': 6}

        If applied to functions not yet decorated with ``@property`` or
        ``@cached_property``, the function is automatically wrapped with
        `property`. Although this is more concise, you will lose intellisense
        in your IDE, and confuse static type checkers, thus explicit use of
        `@property` is recommended.

        >>> from plateforme import BaseModel, computed_field
        >>> class Square(BaseModel):
        ...    width: float
        ...
        ...    # converted to a "property" by "computed_field"
        ...    @computed_field
        ...    def area(self) -> float:
        ...        return round(self.width**2, 2)
        ...
        ...   @area.setter
        ...   def area(self, new_area: float) -> None:
        ...       self.width = new_area**0.5
        ...
        ...   @computed_field(alias='the magic number', repr=False)
        ...   def random_number(self) -> int:
        ...       return random.randint(0, 1000)

        >>> square = Square(width=1.3)
        ... print(repr(square))
        Square(width=1.3, area=1.69)

        >>> print(square.random_number)
        3

        >>> square.area = 4
        ... print(square.model_dump_json(by_alias=True))
        {"width": 2.0, "area": 4.0, "the magic number": 3}

        It is not possible to override a field from a parent class with a
        `computed_field` in the child class. MyPy complains about this behavior
        if allowed, and `dataclasses` doesn't allow this pattern either as
        shown in the example below:

        >>> from plateforme import BaseModel, computed_field
        >>> class Parent(BaseModel):
        ...     a: str

        >>> try:
        ...     class Child(Parent):
        ...         @computed_field
        ...         @property
        ...         def a(self) -> str:
        ...             return 'new a'
        ... except ValueError as e:
        ...     print(repr(e))
        ValueError('you can't override a field with a computed field')

        The private properties decorated with ``@computed_field`` have their
        representation set to false ``repr=False`` by default:

        >>> from functools import cached_property
        >>> from plateforme import BaseModel, computed_field
        >>> class Model(BaseModel):
        ...     foo: int
        ...
        ...     @computed_field
        ...     @cached_property
        ...     def _private_cached_property(self) -> int:
        ...         return -self.foo
        ...
        ...     @computed_field
        ...     @property
        ...     def _private_property(self) -> int:
        ...         return -self.foo

        >>> model = Model(foo=1)
        ... print(repr(model))
        Model(foo=1)

    Note:
        Using MyPy, even with the ``@property`` or ``@cached_property`` applied
        to your function before ``@computed_field``, it may throw a "Decorated
        property not supported" error.
        See https://github.com/python/mypy/issues/1362
    """

    def wrapper(func: Any) -> Any:
        nonlocal alias, alias_priority, slug, title, description, repr

        # Collect computed field information alias priority
        alias_priority = (alias_priority or 2) if alias is not None else None

        # Retrieve computed field information identifier
        name: str | None
        if isinstance(func, property):
            name = getattr(func.fget, '__name__', None)
        else:
            name = getattr(func, '__name__', None)
        identifier = to_name_case(name or alias or slug or title or '')

        # Check if identifier is valid
        if not identifier:
            # Unlike standard fields, computed fields must have a valid
            # identifier to be used in the field information namespace.
            raise PlateformeError(
                "A computed field must have a valid identifier. Either ensure "
                "the decorated function has a name or provide a valid "
                "`alias`, `slug`, or `title` argument.",
                code='field-invalid-config',
            )

        # Update computed field information namespace
        name = name or identifier
        alias = alias or identifier
        slug = slug or to_path_case(identifier)
        title = title or to_title_case(identifier)

        # Validate computed field information namespace
        def validate(key: str, pattern: str, value: str) -> None:
            if re.match(pattern, value):
                return
            raise PlateformeError(
                f"The computed field with identifier {identifier!r} has an "
                f"invalid attribute {key} {value!r} in its configuration. It "
                f"must match a specific pattern defined in the framework "
                f"regular expressions repository.",
                code='field-invalid-config',
            )
        validate('name', RegexPattern.ALIAS, name)
        validate('alias', RegexPattern.ALIAS, alias)
        validate('slug', RegexPattern.SLUG, slug)
        validate('title', RegexPattern.TITLE, title)

        # Unwrap the function and update documentation
        unwrapped = _decorators.unwrap_wrapped_function(func)
        if description is None and unwrapped.__doc__:
            description = inspect.cleandoc(unwrapped.__doc__)

        # Wrap the function if it is not already decorated with "@property"
        # (or another descriptor).
        wrapped_property = _decorators.ensure_property(func)

        # Update reprerentation if not set
        if repr is None:
            repr = False if is_private(prop=wrapped_property) else True

        wrapper_info = ComputedFieldInfo(
            wrapped_property=wrapped_property,
            name=name,
            return_type=return_type,
            alias=alias,
            alias_priority=alias_priority,
            slug=slug,
            title=title,
            description=description,
            examples=examples,
            deprecated=deprecated,
            repr=repr,
            json_schema_extra=json_schema_extra,
        )

        return _decorators.PydanticDescriptorProxy(
            wrapped_property, wrapper_info
        )

    if __func is None:
        return wrapper
    else:
        return wrapper(__func)  # type: ignore[no-any-return]