Skip to content

Instantly share code, notes, and snippets.

@e-dreyer
Created August 3, 2023 10:12
Show Gist options
  • Save e-dreyer/878d2e8de3686495cbd1fc001f2231f7 to your computer and use it in GitHub Desktop.
Save e-dreyer/878d2e8de3686495cbd1fc001f2231f7 to your computer and use it in GitHub Desktop.
ConfigAccessor ABC Python class
from typing import Any, Dict
import yaml
from collections import UserDict
class ConfigAccessor(UserDict):
def __init__(self, file_name: str) -> None:
super().__init__()
self.file_name = file_name
try:
with open(file_name, "r") as config_file:
self.data = yaml.safe_load(config_file)
except FileNotFoundError:
print(f"File {self.file_name} does not exist")
except:
raise
def update(self, other) -> None:
self.data.update(other.data if "data" in other else other)
def __getattr__(self, item) -> Any:
if item in self.data:
return self.data[item]
raise AttributeError(f"'{item} not defined in {self.file_name}")
def __str__(self) -> str:
return str(self.data)
def __repr__(self) -> str:
return repr(self.data)
@e-dreyer
Copy link
Author

e-dreyer commented Aug 8, 2023

This is a simple class to import yaml and json files into. The class raises Appropriate errors showing that the config file missed such key value pair

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment