Skip to content

Settings

plateforme.core.settings

This module provides utilities for managing settings within the Plateforme framework.

LoggingFormatterSettings module-attribute

Logging formatter settings.

LoggingHandlerSettings module-attribute

Logging handler settings.

ADJECTIVES module-attribute

ADJECTIVES = (
    "Apex",
    "Arc",
    "Astro",
    "Atomic",
    "Black",
    "Blue",
    "Call",
    "Cold",
    "Core",
    "Cyber",
    "Dark",
    "Data",
    "Deep",
    "Delta",
    "Dual",
    "Edge",
    "Epsilon",
    "Fast",
    "Flat",
    "Flow",
    "Flux",
    "Gamma",
    "Gen",
    "Gray",
    "Grid",
    "Hard",
    "Hash",
    "Heavy",
    "High",
    "Hot",
    "Hyper",
    "Iron",
    "Kappa",
    "Lab",
    "Lambda",
    "Late",
    "Lead",
    "Lens",
    "Line",
    "Mod",
    "Mass",
    "Max",
    "Mega",
    "Nano",
    "Neo",
    "Net",
    "Neural",
    "Nova",
    "Omega",
    "Port",
    "Prime",
    "Proto",
    "Pull",
    "Quad",
    "Raw",
    "Red",
    "Sharp",
    "Sigma",
    "Solid",
    "Sub",
    "Tech",
    "Var",
    "Wire",
    "Zeta",
)

A list of adjectives used to generate random application titles.

NOUNS module-attribute

NOUNS = (
    "Array",
    "Axis",
    "Base",
    "Bit",
    "Block",
    "Bool",
    "Boot",
    "Buffer",
    "Bus",
    "Byte",
    "Cache",
    "Cell",
    "Chain",
    "Cube",
    "Dict",
    "Diff",
    "Disk",
    "Dock",
    "Eval",
    "Exec",
    "File",
    "Flag",
    "Frame",
    "Func",
    "Gate",
    "Graph",
    "Group",
    "Heap",
    "Hook",
    "Host",
    "Hub",
    "Init",
    "Int",
    "Item",
    "Join",
    "Key",
    "Link",
    "List",
    "Loop",
    "Map",
    "Mesh",
    "Mode",
    "Num",
    "Node",
    "Null",
    "Page",
    "Path",
    "Pipe",
    "Pod",
    "Pool",
    "Proc",
    "Queue",
    "Ram",
    "Ring",
    "Root",
    "Scan",
    "Set",
    "Shell",
    "Stack",
    "Sync",
    "Task",
    "Term",
    "Tree",
    "Word",
)

A list of nouns used to generate random application titles.

ContactInfo

ContactInfo(**data: Any)

Bases: BaseModel

Contact information.

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

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

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

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

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

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

ContactInfoDict

Bases: TypedDict

Contact information dictionary.

name instance-attribute

name: Required[str]

The name of the contact person or organization.

email instance-attribute

email: Email

The email address of the contact person or organization. It must be formatted as a valid email address. Defaults to None.

url instance-attribute

A URL pointing to the contact information. It must be formatted as a valid URL. Defaults to None.

LicenseInfo

LicenseInfo(**data: Any)

Bases: BaseModel

License information.

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

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

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

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

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

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

LicenseInfoDict

Bases: TypedDict

License information dictionary.

name instance-attribute

name: Required[str]

The license name.

identifier instance-attribute

identifier: str

An SPDX license expression. The identifier field is mutually exclusive with the url field. It is available within OpenAPI since version 3.1.0. Defaults to None.

url instance-attribute

A URL pointing to the license information. The url field is mutually exclusive with the identifier field. Defaults to None.

APIRouterSettings

APIRouterSettings(**data: Any)

Bases: BaseModel

Plateforme API router settings.

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

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

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

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

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

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

APISettings

APISettings(**data: Any)

Bases: BaseModel

Plateforme API settings.

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

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

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

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

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

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

LoggingCustomFormatterSettings

LoggingCustomFormatterSettings(**data: Any)

Bases: BaseModel

Logging custom formatter settings.

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

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

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

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

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

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

LoggingDefaultFormatterSettings

LoggingDefaultFormatterSettings(**data: Any)

Bases: BaseModel

Logging default formatter settings.

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

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

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

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

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

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

LoggingJsonFormatterSettings

LoggingJsonFormatterSettings(**data: Any)

Bases: BaseModel

Logging JSON formatter settings.

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

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

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

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

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

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

LoggingSimpleFormatterSettings

LoggingSimpleFormatterSettings(**data: Any)

Bases: BaseModel

Logging simple formatter settings.

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

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

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

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

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

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

LoggingCustomHandlerSettings

LoggingCustomHandlerSettings(**data: Any)

Bases: BaseModel

Logging custom handler settings.

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

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

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

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

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

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

LoggingFileHandlerSettings

LoggingFileHandlerSettings(**data: Any)

Bases: BaseModel

Logging file handler settings.

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

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

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

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

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

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

LoggingStreamHandlerSettings

LoggingStreamHandlerSettings(**data: Any)

Bases: BaseModel

Logging stream handler settings.

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

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

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

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

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

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

LoggingSettings

LoggingSettings(**data: Any)

Bases: BaseModel

Plateforme logging settings.

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

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

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

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

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

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

LoggingSettingsDict

Bases: TypedDict

Plateforme logging settings dictionary.

level instance-attribute

level: Literal[
    "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"
]

The logging level for the application. Defaults to 'INFO'.

filters instance-attribute

filters: dict[str, str]

A dictionary of logging filters used in the application with their names as keys and the fully qualified name of the filter class as values. By default, it includes one built-in filter under the key 'no_errors' that can be overridden. If provided, the custom filters are merged with these defaults. Defaults to an empty dictionary.

formatters instance-attribute

A dictionary of logging formatters used in the application. By default, it includes three built-in formatters under the keys 'default', 'color', and 'json' that can be overridden. If provided, the custom formatters are merged with these defaults. Defaults to an empty dictionary.

handlers instance-attribute

A dictionary of logging handlers used in the application. By default, it includes two built-in handlers under the keys 'stdout' and 'stderr' that can be overridden. If provided, the custom handlers are merged with these defaults. Defaults to an empty dictionary.

NamespaceSettings

NamespaceSettings(**data: Any)

Bases: BaseModel

Plateforme namespace settings.

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

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

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

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

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

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

PackageSettings

PackageSettings(**data: Any)

Bases: BaseModel

Plateforme package settings.

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

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

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

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

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

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

Settings

Bases: BaseSettings

Plateforme application settings.

SettingsDict

Bases: TypedDict

Plateforme application settings dictionary.

context instance-attribute

context: bool

Whether to set up and maintain the application context in the current thread when creating the instance. When enabled, the application context will be set to the current application being initialized, and won't require an explicit context manager. Defaults to True.

debug instance-attribute

debug: bool

Whether to run the application in debug mode. When debug mode is enabled, debug tracebacks will be returned on server and the application will automatically reload when changes are detected in the underlying code. Defaults to False.

logging instance-attribute

Whether to enable logging in the application. When enabled, the application will log messages to the configured handlers. It accepts either a boolean to enable or disable default logging settings or a dictionary with custom logging settings. Defaults to True.

secret_key instance-attribute

secret_key: SecretStr | str

The application secret key. If not provided, a random alphanumeric secret key marked as insecure will be generated. Please note that it must be kept secret and should not be shared, it's insecure to use a secret key in a public repository. Consider using an environment variable instead. Defaults to a random secret key.

title instance-attribute

title: str

The application human-readable title that is used to display the application verbose name and will be added to the generated OpenAPI, visible at /docs. When not provided, a random title will be generated. Defaults to a random title.

summary instance-attribute

summary: str | None

A short summary of the application. It will be added to the generated OpenAPI, visible at /docs. Defaults to None.

description instance-attribute

description: str | None

A description of the application. Supports Markdown (using CommonMark syntax). It will be added to the generated OpenAPI, visible at /docs. Defaults to None.

version instance-attribute

version: str

The application version. It is used to define the version of the application, not the version of the OpenAPI specification or the version of the Plateforme framework being used. It will be added to the generated OpenAPI, visible at /docs. Defaults to '0.1.0'.

contact instance-attribute

contact: ContactInfo | ContactInfoDict | str | None

The contact information for the application exposed API. It can be provided either as a string with the contact name and optionally an email address, or as a dictionary. The following fields will be added to the generated OpenAPI, visible at /docs: - name (str): The name of the contact person or organization. If not provided, it defaults to an empty string. - url (str): An URL pointing to the contact information. It must be formatted as a valid URL. - email (str): The email address of the contact person or organization. It must be formatted as a valid email address. Defaults to None.

license instance-attribute

license: LicenseInfo | LicenseInfoDict | str | None

The license information for the application exposed API. It can be provided either as a string with the license name, or as a dictionary. The following fields will be added to the generated OpenAPI, visible at /docs: - name (str): The license name used for the API. - identifier (str): An SPDX license expression for the API. The identifier field is mutually exclusive of the url field. Available since OpenAPI 3.1.0. - url (str): An URL to the license used for the API. This must be formatted as a valid URL. Defaults to None.

terms_of_service instance-attribute

terms_of_service: str | None

A URL to the Terms of Service for the application exposed API. It will be added to the generated OpenAPI, visible at /docs. Defaults to None.

language instance-attribute

language: str

The application language code. Defaults to 'en'.

timezone instance-attribute

timezone: str

The application time zone code. Defaults to 'UTC'.

namespaces instance-attribute

The application namespaces to load. Each namespace can be provided either as a string for the namespace name or a tuple with the namespace name and its settings. The namespace name is used to group package resources and services within the application to avoid name collisions. The default namespace uses the empty string as its name ''. The namespace settings are used to override the default namespace implementation configuration. Defaults to an empty list.

packages instance-attribute

The application packages to load. Each package can be provided either as a string for the package name or a tuple with the package name and its settings. The package name is used to load the package with its resources and services within the application. The package settings are used to override the default package implementation configuration. The default special package symbol $ is used to reference the application caller package and load its module resources and services. Defaults to a list with the special package symbol '$'.

auto_import_dependencies instance-attribute

auto_import_dependencies: bool

Whether to automatically import dependencies of the application packages. Auto-imported package dependencies are implemented with their default settings. Defaults to True.

auto_import_namespaces instance-attribute

auto_import_namespaces: bool

Whether to automatically import and create missing namespace configurations for packages within the application. Defaults to True.

api instance-attribute

The API settings. Defaults to the default API settings.

api_max_depth instance-attribute

api_max_depth: int

The maximum depth to walk through the resource path to collect manager methods from resource dependencies. It is used to generate the API routes for resources within the application. Defaults to 2.

api_max_selection instance-attribute

api_max_selection: int

The limit of resources to return for the API route selections. It is used when generating the API routes for resources within the application to avoid too many resources being returned. Defaults to 20.

deprecated instance-attribute

deprecated: bool | None

Whether the application is deprecated. Defaults to None.

database_engines instance-attribute

database_engines: (
    EngineMap | dict[str, Path | str] | Path | str
)

The application database engines. It accepts either: - A string with the database engine URL such as ':memory:' for an in-memory SQLite database, a path to a SQLite database file, or a database URL for other database engines. - A dictionary with the database engine URL for the default engine and other engines. Defaults to ':memory:'.

database_routers instance-attribute

database_routers: Sequence[str]

The application database routers. A list of either module names from which to import database routers, or fully qualified names of database routers. Defaults to an empty list.

generate_secret_key

generate_secret_key(
    length: int = 32, secure: bool = False
) -> str

Generate a secure alphanumeric secret key of the given length.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/settings.py
def generate_secret_key(length: int = 32, secure: bool = False) -> str:
    """Generate a secure alphanumeric secret key of the given length."""
    import secrets

    characters = string.ascii_letters + string.digits
    key = ''.join(secrets.choice(characters) for _ in range(length))
    if not secure:
        return f'insecure={key}'
    return key

generate_seed_from_path

generate_seed_from_path(path: str | None = None) -> int

Generates a reproducible seed from a system path.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/settings.py
def generate_seed_from_path(path: str | None = None) -> int:
    """Generates a reproducible seed from a system path."""
    import hashlib
    import sys

    if path is None:
        path = sys.path[0] if sys.path else ''
    seed = int(hashlib.sha256(path.encode()).hexdigest(), 16)
    return seed

generate_title

generate_title() -> str

Generate a random title.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/settings.py
def generate_title() -> str:
    """Generate a random title."""
    from random import Random
    generator = Random(generate_seed_from_path())
    title_adjective: str = generator.choice(ADJECTIVES)
    title_noun: str = generator.choice([
        noun for noun in NOUNS if noun[0] != title_adjective[0]
    ])
    return f'{title_adjective} {title_noun}'

merge_settings

merge_settings(
    settings: _T, *others: BaseModel | None, **update: Any
) -> _T

Merge multiple settings into a single settings instance.

It copies the provided settings model instance and merges other settings model instances into for matching fields. The last settings model instance has precedence over the previous ones. Additional settings can be provided as keyword arguments, where a DefaultPlaceholder can be used to set a default value for a field when no previous settings have set it.

Parameters:

Name Type Description Default
settings _T

The settings model instance to copy and use as a base.

required
*others BaseModel | None

The other settings model instances to merge into the base.

()
**update Any

Values to add/modify within the new model. Note that the integrity of the data is not validated when creating the new model. Data should be trusted or pre-validated in this case. Additionaly it can include DefaultPlaceholder values to set default values for settings model fields.

{}

Returns:

Type Description
_T

The merged settings model instance.

Raises:

Type Description
ValidationError

If the merged settings are invalid.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/settings.py
def merge_settings(
    settings: _T,
    *others: BaseModel | None,
    **update: Any,
) -> _T:
    """Merge multiple settings into a single settings instance.

    It copies the provided settings model instance and merges other settings
    model instances into for matching fields. The last settings model instance
    has precedence over the previous ones. Additional settings can be provided
    as keyword arguments, where a `DefaultPlaceholder` can be used to set a
    default value for a field when no previous settings have set it.

    Args:
        settings: The settings model instance to copy and use as a base.
        *others: The other settings model instances to merge into the base.
        **update: Values to add/modify within the new model. Note that the
            integrity of the data is not validated when creating the new model.
            Data should be trusted or pre-validated in this case. Additionaly
            it can include `DefaultPlaceholder` values to set default values
            for settings model fields.

    Returns:
        The merged settings model instance.

    Raises:
        ValidationError: If the merged settings are invalid.
    """
    # Create a new settings model instance
    data = settings.model_dump(exclude_defaults=True)

    # Merge other settings
    for other in others:
        if other is None:
            continue
        for key in other.model_fields_set:
            if key not in settings.model_fields:
                continue
            settings_field = settings.model_fields[key]
            other_field = other.model_fields[key]
            if settings_field.annotation == other_field.annotation:
                data[key] = getattr(other, key)

    # Update settings
    for key, value in update.items():
        if key not in settings.model_fields:
            continue
        if isinstance(value, DefaultPlaceholder):
            if key in data:
                continue
            data[key] = value.value
        else:
            data[key] = value

    # Validate settings
    return settings.model_construct(**data)

plateforme.core.loaders

This module provides utilities for managing loaders used in settings within the Plateforme framework.

LoaderInfo

LoaderInfo(name: str, *, static: bool = True)

Bases: Representation

Information about a loader.

This class is used to store information about an object that is loaded using a fullname. It is used to serialize and deserialize the object.

Attributes:

Name Type Description
name

The fullname of the object.

static

Whether the object was loaded statically.

Initialize the loader information.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/loaders.py
def __init__(self, name: str, *, static: bool = True) -> None:
    """Initialize the loader information."""
    self.name = name
    self.static = static

Loader

Loader(type_: type[_T] = object)

Bases: Generic[_T]

A loader for objects.

This class is used to load objects from a fullname. It is used to serialize and deserialize the object.

Attributes:

Name Type Description
type_ type[_T]

The type of the object to load.

Initialize the loader.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/loaders.py
def __init__(self, type_: type[_T] = object) -> None:  # type: ignore
    """Initialize the loader."""
    self.type_ = type_

serialize

serialize(
    obj: _T, info: SerializationInfo | None = None
) -> LoaderInfo | str

Serialize the loaded object.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/loaders.py
def serialize(
    self,
    obj: _T,
    info: SerializationInfo | None = None,
) -> LoaderInfo | str:
    """Serialize the loaded object."""
    if info and info.mode == 'python':
        return obj
    if loader := getattr(obj, '__config_loader__', None):
        assert isinstance(loader, LoaderInfo)
        return loader.name

    raise ValueError(
        f"Cannot serialize object {obj!r} in JSON mode without a loader "
        f"information."
    )

validate

validate(obj: Any, *, strict: bool | None = None) -> _T

Validate and load an object.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/loaders.py
def validate(
    self,
    obj: Any,
    *,
    strict: bool | None = None,
) -> _T:
    """Validate and load an object."""
    # Load object
    if isinstance(obj, (LoaderInfo, str)):
        loader = LoaderInfo(str(obj))
        instance = import_object(loader.name)
        if instance is self.type_:
            instance = instance()
        object.__setattr__(instance, '__config_loader__', loader)
    elif strict:
        raise ValueError(
            f"Cannot load object {obj!r} without a loader information."
        )
    else:
        instance = obj

    # Validate object instance
    if not self.validate_instance(instance, strict=strict):
        raise ValueError(
            f"Loaded object {instance!r} is not an instance of "
            f"{self.type_!r}."
        )
    return instance  # type: ignore[no-any-return]

validate_instance

validate_instance(
    obj: Any, *, strict: bool | None = None
) -> bool

Validate an object instance against the loader type.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/loaders.py
def validate_instance(
    self,
    obj: Any,
    *,
    strict: bool | None = None,
) -> bool:
    """Validate an object instance against the loader type."""
    origin = typing.get_origin(self.type_)
    if origin is None:
        return isinstance(obj, self.type_)
    if origin in (type, Type):
        args = typing.get_args(self.type_)
        return issubclass(obj, args[0])

    try:
        return isinstance(obj, origin)
    except TypeError:
        if strict:
            return False
    return True