Advertisement
mbazs

Python config singleton

Dec 29th, 2020
1,248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. import yaml
  2. import os
  3. import easydict
  4. import threading
  5.  
  6. CONFIGS = [
  7.     '/etc/avgjoe/useful_stuff/config.yaml',
  8.     '~/.config/avgjoe/useful_stuff/config.yaml',
  9.     '~/.useful_stuff_config.yaml']
  10.  
  11.  
  12. class Config:
  13.     __cfg = None
  14.     __lock = threading.Lock()
  15.  
  16.     @classmethod
  17.     def get(cls):
  18.         with cls.__lock:
  19.             if cls.__cfg is None:
  20.                 cls.__cfg = Config.load()
  21.         return cls.__cfg
  22.  
  23.     @staticmethod
  24.     def load():
  25.         for conf in CONFIGS:
  26.             try:
  27.                 with open(os.path.expanduser(conf), 'r') as f:
  28.                     cfg = easydict.EasyDict(yaml.safe_load(f))
  29.                 break
  30.             except IOError as e:
  31.                 pass
  32.         return cfg
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement