pydantic_sweep.convert

Functions

model_to_python(→ str)

Generate python code for a pydantic model.

load(→ pydantic.BaseModel)

Load a pydantic model from a file.

write(→ None)

Write a model to a file.

Module Contents

pydantic_sweep.convert.model_to_python(model: pydantic.BaseModel, *, name: str = 'model', exclude_unset: bool = True, exclude_defaults: bool = False, include: collections.abc.Collection[str] | collections.abc.Mapping[str, Any] | None = None) str[source]

Generate python code for a pydantic model.

This function generates python code that instantiates a given model. This is, for example, useful to switch json/yaml configuration files to Python-native ones.

Parameters:
  • model – The model that we want to convert to Python code

  • name – The name of the variable to which we assign the instantiated model.

  • exclude_defaults – Whether to exclude default arguments.

  • include – Additional fields to include.

Returns:

The corresponding python code including imports.

pydantic_sweep.convert.load(source: os.PathLike | str, /, *, model: str) pydantic.BaseModel[source]

Load a pydantic model from a file.

Parameters:
  • source – The file that we want to read the model from. Supported extensions are .json, .yaml, .yml, .toml, and .py.

  • model – The model that we want to load. This is either a path to a module with dot-notation (e.g., my_module.MyModel) or, for python files, the name of the variable where the model is stored in the file.

Returns:

The loaded pydantic model.

pydantic_sweep.convert.write(target: os.PathLike | str, /, *, model: pydantic.BaseModel, yaml_options: dict[str, Any] | None = None, exclude_unset: bool = True, exclude_defaults: bool = False) None[source]

Write a model to a file.

Parameters:
  • target – The file to write to. Supported extensions are .json, .yaml, .yml, .toml and .py.

  • model – The pydantic model that we want to write to the file.

  • yaml_options – Optional keyword-arguments passed to yaml.dump.

  • exclude_unset – Exclude fields that don’t have a value set.

  • exclude_defaults – Exclude fields that have the default value set.