Created
August 3, 2023 10:12
-
-
Save e-dreyer/878d2e8de3686495cbd1fc001f2231f7 to your computer and use it in GitHub Desktop.
ConfigAccessor ABC Python class
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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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