Skip to content

Instantly share code, notes, and snippets.

@antonagestam
Last active October 7, 2019 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonagestam/65a2aeb697e307bbcbe090c2437c7a4f to your computer and use it in GitHub Desktop.
Save antonagestam/65a2aeb697e307bbcbe090c2437c7a4f to your computer and use it in GitHub Desktop.
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")
typing-extensions
immutables
pyhcl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment