Skip to content

Instantly share code, notes, and snippets.

@ericvenarusso
Created November 19, 2021 02:52
Show Gist options
  • Save ericvenarusso/dcaefd5495230a33ef2eb2bdca262011 to your computer and use it in GitHub Desktop.
Save ericvenarusso/dcaefd5495230a33ef2eb2bdca262011 to your computer and use it in GitHub Desktop.
Example using Pydantic as Schema for YAML Files
name: 'Eric Venarusso'
age: '21'
sex: 'male'
sports:
- name: 'soccer'
team:
name: 'corinthians'
- name: 'basketball'
import yaml
from typing import List, Optional
from pydantic import BaseModel, StrictStr
class Team(BaseModel):
name: Optional[StrictStr] = None
class Sports(BaseModel):
name: StrictStr
team: Optional[Team]
class Person(BaseModel):
name: StrictStr
age: int
sex: StrictStr
sports: List[Sports]
def read_yaml(file_path: str) -> dict:
with open(file_path, 'r') as stream:
config = yaml.safe_load(stream)
return Person(**config).dict()
config = read_yaml('config.yaml')
print(config)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment