Created
November 19, 2021 02:52
-
-
Save ericvenarusso/dcaefd5495230a33ef2eb2bdca262011 to your computer and use it in GitHub Desktop.
Example using Pydantic as Schema for YAML Files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: 'Eric Venarusso' | |
age: '21' | |
sex: 'male' | |
sports: | |
- name: 'soccer' | |
team: | |
name: 'corinthians' | |
- name: 'basketball' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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