Advertisement
Dori_mon

Yaml Config System Python

Mar 10th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. import yaml
  2.  
  3. class Config:
  4.  
  5.     _file_name = None
  6.  
  7.     _content = {}
  8.     _default = {}
  9.  
  10.     def __init__(self, file_name:str='config.yml'):
  11.         self._file_name = file_name
  12.  
  13.     def load(self):
  14.         with open(self._file_name, 'a+', encoding='utf8') as config_file:
  15.             self._content = yaml.load(config_file)
  16.             if self._content is None:
  17.                 self._content = {}
  18.  
  19.     def set_default(self, key:str, value):
  20.         parse = self._parse_content_and_key(key, obj=self._default)
  21.         parse[0][parse[1]] = value
  22.    
  23.     def set_defaults(self, defaults):
  24.         for key in defaults:
  25.             self.set_default(key, defaults[key])
  26.  
  27.     def copy_defaults(self):
  28.         for key in self._default:
  29.             if key not in self._content:
  30.                 self._content[key] = self._default[key]
  31.    
  32.     def save(self):
  33.         with open(self._file_name, 'w+', encoding='utf8') as config_file:
  34.             yaml.dump(self._content, config_file, default_flow_style=False)
  35.        
  36.     def get(self, key, default=None):
  37.         parse = self._parse_content_and_key(key)
  38.         return parse[0].get(parse[1], default)
  39.    
  40.     def _parse_content_and_key(self, key, obj=None):
  41.  
  42.         obj = self._content if obj is None else obj
  43.         final_key = None
  44.  
  45.         split = key.split('.')
  46.         for i in range(0, len(split)):
  47.             if i + 1 == len(split):
  48.                 final_key = split[i]
  49.                 break
  50.            
  51.             if split[i] not in obj:
  52.                 obj[split[i]] = {}
  53.  
  54.             obj = obj[split[i]]
  55.        
  56.         return obj, final_key
  57.    
  58.  
  59. CONFIG = Config()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement