parse yaml files with pydantic
Project description
pydantic-yaml-parser
Install
pip install pydantic_yaml_parser
Background & Usage
1. Loading YAML into Pydantic models
To load YAML into a Pydantic model, you have to first convert the YAML string 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 using pyyaml:
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'])])
2. The Pydantic validation error message
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!
3. Human readable error messages with pydantic_yaml_parser
When you use pydantic_yaml_parser
you get an error message that is
much 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.3.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | e9235d3152f629f038753aa56feab9566bf09bccb5effe886d00dc3f5e99d46f |
|
MD5 | 4ddcd1085cb7bab0a70cfd7a9888a616 |
|
BLAKE2b-256 | 2488120c13c55f19b821343c33b5628b31e1ab591979df0bd6b0306448bdc448 |
Hashes for pydantic_yaml_parser-0.0.3-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | f70fbda655bda1596f03e9b6c192312388b9c62040cf7a505c6762576b8c49ca |
|
MD5 | 20a0a5d62afaa54efe5676e8f9325a44 |
|
BLAKE2b-256 | a110b4423935aa1d75249b0ee16d22606d7b607325612c655aa478356ec5f919 |