Last active
October 7, 2019 20:22
-
-
Save antonagestam/65a2aeb697e307bbcbe090c2437c7a4f to your computer and use it in GitHub Desktop.
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 | |
from typing import Mapping | |
import hcl | |
from immutables import Map | |
from typing_extensions import Final | |
class Settings: | |
__frozen = False | |
def __init__(self, config: Mapping[str, Any]) -> None: | |
self.__mapping: Map[str, Any] = Map( | |
{k: Settings(v) if isinstance(v, Mapping) else v for k, v in config.items()} | |
) | |
self.__dict__ = {**self.__mapping, **self.__dict__} | |
self.__frozen = True | |
def __repr__(self) -> str: | |
return repr(self.__mapping) | |
def __getattr__(self, item): | |
if item == "__frozen": | |
return self.__frozen | |
try: | |
return self.__mapping[item] | |
except KeyError: | |
raise AttributeError(f"'Settings' object has no attribute '{item}'") | |
def __setattr__(self, key, value): | |
if self.__frozen: | |
raise TypeError(f"Can't set attribute '{key}' on 'Settings' object") | |
super().__setattr__(key, value) | |
def from_file(path) -> Settings: | |
with open(path, "r") as f: | |
return Settings(hcl.loads(f.read())) | |
settings: Final = from_file("config.hcl") |
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
typing-extensions | |
immutables | |
pyhcl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment