Skip to content

Instantly share code, notes, and snippets.

@Miladiouss
Last active January 3, 2023 20:45
Show Gist options
  • Save Miladiouss/39ad8bbe1546e215307f8b7eef35fb31 to your computer and use it in GitHub Desktop.
Save Miladiouss/39ad8bbe1546e215307f8b7eef35fb31 to your computer and use it in GitHub Desktop.
Load a YAML file and convert it to a Python object. Ideal for nested datasets since working with nested dictionaries is not user-friendly. Works with IDE auto-completion recommendation systems. The example below is loading a config file.
from pathlib import Path
import yaml
here = Path(__file__).resolve().parent
with open(here / './config.yaml', 'r') as stream:
config_dict = yaml.safe_load(stream)
class Struct:
def __init__(self, **kwargs):
for key, value in kwargs.items():
if isinstance(value, dict):
self.__dict__[key] = Struct(**value)
else:
self.__dict__[key] = value
config = Struct(**config_dict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment