I would like to load a YAML file and create a Pydantic BaseModel object. I would like to know if it is possible to reuse a variable inside the YAML file, for example:
YAML file
config:
variables:
root_level: DEBUG
my_var: "TEST"
handlers_logs:
- class: $my_var #<--- here
level_threshold: STATS
block_level_filter: true
disable: false
args:
hosts: $my_var #<--- here
topic: _stats
My code:
import os
from pprint import pprint
import yaml
from pydantic import BaseModel
from typing import Dict
from typing import Optional
from yaml.parser import ParserError
class BaseLogModel(BaseModel):
class Config:
use_enum_values = True
allow_population_by_field_name = True
class Config(BaseLogModel):
variables: Optional[Dict[str, str]]
handlers_logs: Any
def load_config(filename) -> Optional[Config]:
if not os.path.exists(filename):
return None
with open(filename) as f:
try:
config_file = yaml.load(f.read(), Loader=yaml.SafeLoader)
if config_file is not None and isinstance(config_file, dict):
config_data = config_file["config"]
else:
return None
except ParserError as e:
return None
return Config.parse_obj(config_data)
def main():
config = load_config("config.yml")
pprint(config)
Output:
Config(variables={'root_level': 'DEBUG', 'my_var': 'TEST'}, handlers_logs=[{'class': '$my_var', 'level_threshold': 'STATS', 'block_level_filter': True, 'disable': False, 'args': {'hosts': '$my_var', 'topic': '_stats'}}])
Instead of the variable $my_var
I would like there to be "TEST"
, this way I wouldn't need to rewrite the same value every time. Is it possible to do this with Pydantic or some other YAML library?