parse yaml files with pydantic
Project description
pydantic-yaml-parser
Install
pip install pydantic_yaml_parser
Background & Usage
To load YAML into a Pydantic model, you have to first convert the YAML to a dict. For example, given the below yaml file:
yaml_string="""
setting_1: Hello
setting_2:
- kind: name
sublist:
- first
- second
"""
You might define a Pydantic model to represent it like this:
from pydantic import BaseModel
from typing import List
class Setting2(BaseModel):
kind: str
sublist: List
class Test(BaseModel):
setting_1: str
setting_2: List[Setting2]
You can load the yaml file into a dict, and into the Pydantic model like so:
import yaml
yml_dict = yaml.safe_load(yaml_string)
# use `parse_obj` to load a dict
Test.parse_obj(yml_dict)
Test(setting_1='Hello', setting_2=[Setting2(kind='name', sublist=['first', 'second'])])
However, let’s say there is an error in your yaml file such that you
accidentally set sublist
to false
, instead of setting sublist
to
list
type, you will get an error message that looks like this:
yaml_string="""
setting_1: ok
setting_2:
- kind: name
sublist: false
"""
yaml_dict_error = yaml.safe_load(yaml_string)
Test.parse_obj(yaml_dict_error)
ValidationError: 1 validation error for Test
setting_2 -> 0 -> sublist
value is not a valid list (type=type_error.list)
This error message is a bit confusing, especially for those with no
prior experience with pydantic! However when you use
pydantic_yaml_parser
you get something a bit clearer:
from pydantic_yaml_parser.yaml import YamlModel
class Test(YamlModel):
setting_1: str
setting_2: List[Setting2]
Test.from_dict(yaml_dict_error)
ValueError: Configuration error(s) for YAML:
- value is not a valid list: `sublist` for element 0 in the list for `setting_2`
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for pydantic-yaml-parser-0.0.2.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | e54322504d843bf54c0b8cc660872b0f92b70b66939fc91af9657752252d33ff |
|
MD5 | a1a224fd15285515a72e18417f45af20 |
|
BLAKE2b-256 | 3b154cd71b42e3beaff8838a41d82e761022780aef261806e7e801d1ba74e21f |
Hashes for pydantic_yaml_parser-0.0.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 16371a24533aace9e85f0777db0f07bf6f82e3b23e65681de73fc626c0fefb6b |
|
MD5 | cd352d43d7a48e99b5f1f2cc188bde9b |
|
BLAKE2b-256 | be872f44421d976b8d7382276d0666283b7e8336c9b20daa857363fcae9b1576 |