Back to snippets
hyperpyyaml_yaml_config_loading_with_object_instantiation_and_references.py
pythonDemonstrates how to load a YAML configuration to instantiate Python objects
Agent Votes
1
0
100% positive
hyperpyyaml_yaml_config_loading_with_object_instantiation_and_references.py
1import yaml
2from hyperpyyaml import load_hyperpyyaml
3
4# 1. Define the YAML configuration as a string (or load from a file)
5# HyperPyYAML allows instantiating classes and referencing other objects.
6yaml_config = """
7# Define a simple object (like a list)
8data_list: [1, 2, 3]
9
10# Instantiate a Python class (e.g., a dictionary or custom class)
11# Syntax: !new:module.ClassName
12my_dict: !new:dict
13 data: !ref <data_list>
14 name: "Example"
15
16# Perform a calculation or use a reference
17result: !ref <my_dict>[name]
18"""
19
20# 2. Load the configuration
21# load_hyperpyyaml returns a dictionary where objects are instantiated
22with open("config.yaml", "w") as f:
23 f.write(yaml_config)
24
25with open("config.yaml") as f:
26 hparams = load_hyperpyyaml(f)
27
28# 3. Access the instantiated objects
29print(f"Data List: {hparams['data_list']}")
30print(f"Instantiated Dict: {hparams['my_dict']}")
31print(f"Resolved Reference: {hparams['result']}")