xtl.common.options module#

xtl.common.options.Option(*, default=PydanticUndefined, default_factory=PydanticUndefined, name=PydanticUndefined, desc=PydanticUndefined, examples=PydanticUndefined, alias=PydanticUndefined, exclude=PydanticUndefined, repr=PydanticUndefined, deprecated=PydanticUndefined, validate_default=PydanticUndefined, choices=PydanticUndefined, gt=PydanticUndefined, ge=PydanticUndefined, lt=PydanticUndefined, le=PydanticUndefined, multiple_of=PydanticUndefined, allow_inf_nan=PydanticUndefined, max_digits=PydanticUndefined, decimal_places=PydanticUndefined, length=PydanticUndefined, min_length=PydanticUndefined, max_length=PydanticUndefined, regex=PydanticUndefined, path_exists=PydanticUndefined, path_is_file=PydanticUndefined, path_is_dir=PydanticUndefined, path_is_absolute=PydanticUndefined, cast_as=PydanticUndefined, validator=PydanticUndefined, strict=PydanticUndefined, formatter=PydanticUndefined, extra=PydanticUndefined)[source]#

Create a pydantic.Field() with custom validation, serialization and more intuitive metadata handling.

Custom validation and serialization functions are stored in the json_schema_extra attribute of the field and are applied to the model if it is of type Options. If an Option field is used in a model that directly inherits from pydantic.BaseModel, then all custom validation and serialization will simply be ignored.

Parameters:
  • default (Any | None) – Default value for the field.

  • default_factory (Callable[[], Any] | Callable[[dict[str, Any]], Any] | None) – A callable to generate the default value.

  • name (str | None) – Name of the field (equivalent to title in pydantic.Field()).

  • desc (str | None) – Description of the field (equivalent to description in pydantic.Field()).

  • examples (list[Any] | None) – Example values for this field.

  • alias (str | None) – Alias for the field (equivalent to serialization_alias in pydantic.Field()).

  • exclude (bool | None) – Exclude this field from serialization.

  • repr (bool) – Include this field in the model’s __repr__ method.

  • deprecated (deprecated | str | bool | None) – Deprecation message for the field.

  • validate_default (bool | None) – Whether to validate the default value.

  • choices (str | tuple[Any, ...] | None) – Iterable of valid values constraint for the field.

  • gt (SupportsGt | None) – Greater than constraint for numeric fields.

  • ge (SupportsGe | None) – Greater than or equal to constraint for numeric fields.

  • lt (SupportsLt | None) – Less than constraint for numeric fields.

  • le (SupportsLe | None) – Less than or equal to constraint for numeric fields.

  • multiple_of (float | None) – Multiple of constraint for numeric fields.

  • allow_inf_nan (bool | None) – Allow inf and nan values for numeric fields.

  • max_digits (int | None) – Maximum number of total digits for decimal fields.

  • decimal_places (int | None) – Maximum number of decimal places for decimal fields.

  • length (int | None) – Length constraint for iterable fields.

  • min_length (int | None) – Minimum length constraint for iterable fields.

  • max_length (int | None) – Maximum length constraint for iterable fields.

  • regex (str | Pattern[str] | None) – Regular expression pattern for string fields.

  • path_exists (bool | None) – Check if the path exists for path fields.

  • path_is_file (bool | None) – Check if the path is a file for path fields.

  • path_is_dir (bool | None) – Check if the path is a directory for path fields.

  • path_is_absolute (bool | None) – Check if the path is absolute for path fields.

  • cast_as (type | Callable | None) – Type or callable to cast the value to prior to validation.

  • validator (BeforeValidator | AfterValidator | Iterable[BeforeValidator | AfterValidator] | None) – Custom validator function for the field.

  • strict (bool | None) – Strict type checking (i.e., no implicit conversion/type coercion).

  • formatter (Callable | None) – Custom serializer function for the field.

  • extra (dict[str, int | float | str | bool | None | list[JsonValue] | dict[str, int | float | str | bool | None | list[JsonValue] | JsonDict]] | Callable[[dict[str, int | float | str | bool | None | list[JsonValue] | dict[str, int | float | str | bool | None | list[JsonValue] | JsonDict]]], None] | None) – Extra JSON schema information (equivalent to json_schema_extra in pydantic.Field()).

Returns:

A pydantic.FieldInfo object with custom validation and metadata handling.

Raises:

ValueError – If neither default nor default_factory is provided.

Return type:

FieldInfo

pydantic model xtl.common.options.Options[source]#

Bases: BaseModel

Base class for storing various configuration options. This class provides validation and serialization through Pydantic. Custom validators and serializers are also supported (see Option for more details).

Fields can be defined using Option or pydantic.Field(), but custom validation will only be applied if Option is used.

In addition to the standard Pydantic serialization methods, this class can also be serialized to a TOML file. Deserialization is possible from Python dictionaries, JSON and TOML strings.

Parsing of environment variables in string values is possible by setting parse_env=True in the constructor. This will replace any environment variable references in the format ${VARIABLE} with their values. If the variable is not found, it will be replaced with an empty string. The default behavior is to not parse environment variables.

Config:
  • arbitrary_types_allowed: bool = True

  • validate_default: bool = True

  • validate_assignment: bool = True

  • use_enum_values: bool = True

Validators:
  • _custom_validation » all fields

__init__(**data)[source]#

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:

data (Any)

Return type:

None

classmethod from_dict(data)[source]#

Create a new Options object from a dictionary. Nested dictionaries can be used to create nested Options objects.

Parameters:

data (dict[str, Any]) – Dictionary containing the values to create the config with.

Returns:

An Options object.

Return type:

Self

classmethod from_json(s)[source]#

Create a new Options object from a JSON string or file.

Parameters:

s (str | Path) – JSON string or path to a JSON file.

Returns:

An Options object.

Raises:
  • json.JSONDecodeError – If the JSON is invalid.

  • FileNotFoundError – If the file does not exist.

Return type:

Self

classmethod from_toml(s)[source]#

Create a new Options object from a TOML string or file.

Parameters:

s (str | Path) – TOML string or path to a TOML file.

Returns:

An Options object.

Raises:
  • toml.TomlDecodeError – If the TOML is invalid.

  • FileNotFoundError – If the file does not exist.

Return type:

Self

to_dict(by_alias=True)[source]#

Convert the Options to a dictionary. Nested Options objects will be converted to nested dictionaries.

Parameters:

by_alias (bool) – Whether to use field aliases in the output dictionary.

Returns:

A dictionary representation of the Options.

Return type:

dict[str, Any]

to_json(filename=None, overwrite=False, keep_file_ext=False, indent=4, by_alias=True)[source]#

Write the Options to a JSON file. If filename is not provided, then the JSON will be returned as a string.

Parameters:
  • filename (str | Path | None) – Optional output path for the JSON file.

  • comments – Include comments in the JSON file.

  • overwrite (bool) – Overwrite the file if it already exists.

  • keep_file_ext (bool) – Keep the file extension if filename is provided.

  • indent (int | None) – Indentation level for the JSON string. If None, then the JSON will be compact.

  • by_alias (bool) – Whether to use field aliases in the output JSON.

Returns:

Either the JSON string or the output path.

Raises:

FileExistsError – If the file already exists and overwrite is False.

Return type:

str | Path

to_toml(filename=None, comments=False, overwrite=False, keep_file_ext=False)[source]#

Write the Options to a TOML file. If filename is not provided, then the TOML will be returned as a string.

Parameters:
  • filename (str | Path | None) – Optional output path for the TOML file.

  • comments (bool) – Include comments in the TOML file.

  • overwrite (bool) – Overwrite the file if it already exists.

  • keep_file_ext (bool) – Keep the file extension if filename is provided.

Returns:

Either the TOML string or the output path.

Raises:

FileExistsError – If the file already exists and overwrite is False.

Return type:

str | Path