Created
October 26, 2015 08:08
-
-
Save ktaragorn/9cf6d368378b0f65a3a0 to your computer and use it in GitHub Desktop.
A nice way to keep app config in yaml format and load it into a attr accessible object
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
import yaml | |
from awesome_print.awesome_print import format as frmt | |
class AttrDict(object): | |
def __init__(self, dct): | |
self.dict = dct | |
def __repr__(self): | |
return repr(self.dict) | |
def __str__(self): | |
return frmt(self.dict) | |
def __getattr__(self, attr): | |
print attr | |
try: | |
val = self.dict[attr] | |
if isinstance(val, dict): | |
val = AttrDict(val) | |
return val | |
except KeyError: | |
raise AttributeError | |
with open("settings.yaml", "r") as f: | |
settings = AttrDict(yaml.load(f)) | |
# to use, from config import settings ; settings.secrets.twitter.key |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an improved version of http://stackoverflow.com/a/11049696/1520364