Skip to content

Instantly share code, notes, and snippets.

@wd60622
Last active October 19, 2022 20:31
Show Gist options
  • Save wd60622/d8cc702f48e51d9a1e687ca1b6b66212 to your computer and use it in GitHub Desktop.
Save wd60622/d8cc702f48e51d9a1e687ca1b6b66212 to your computer and use it in GitHub Desktop.
Using Pydantic to define and read in yaml configuration files. Provides built in config validation!
from yaml_base_model import YamlBaseModel
from pydantic import BaseModel
from typing import List
from enum import Enum
class Category(Enum):
GREETING: str = "Greeting"
CODE: str = "Code"
class Response(BaseModel):
"""Dummy key, value response"""
key: str
value: str
category: Category = Category.GREETING
class Config(YamlBaseModel):
"""Dummy config file structure to read in"""
data: List[Response]
if __name__ == "__main__":
# Sucessfully loaded config
config = Config.from_yaml("./config.yaml")
assert isinstance(config, Config)
assert isinstance(config.data[0], Response)
from pydantic import ValidationError
# Fail to load config
file = "./incorrect_config.yaml"
try:
incorrect_config = Config.from_yaml(file)
except ValidationError:
print(f"Unable to load {file}. Incountered a validation error")
data:
- key: Hello
value: World
- key: Python
value: Pydantic
category: Code
data:
- key: Hello
value: World
- Fail to load because this is just a string
data:
- key: Hello
value: World
category: Unsupported category. i.e. Free validation!
from pydantic import BaseModel
import yaml
from typing import Union
from pathlib import Path
class YamlBaseModel(BaseModel):
"""Pydantic.BaseModel with yaml read class method.
Allows for documentation of yaml config structure and easy read in but with the pydantic runtime validation.
"""
@classmethod
def from_yaml(cls, file: Union[str, Path]) -> "YamlBaseModel":
file = Path(file)
with open(file, "r") as f:
data = yaml.safe_load(f)
return cls.parse_obj(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment