|
- #!/usr/bin/env python3
- # -*- coding: utf-8; mode: python; tab-width: 4; indent-tabs-mode: nil -*-
- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
-
-
- import os
- import json
-
-
- class DictNodeWrapper(object):
- def __init__(self, node):
- self._node = node
-
- def __getattr__(self, attr):
- if attr in self._node:
- if isinstance(self._node[attr], dict):
- return DictNodeWrapper(self._node[attr])
- else:
- return self._node[attr]
- return None
-
- def __getitem__(self, attr):
- return self.__getattr__(attr)
-
- def __contains__(self, item):
- return (item in self._node)
-
- class Config(object):
- def __init__(self, config=None):
- super(Config, self).__init__()
-
- if not config:
- raise Exception("The input object is invalid")
-
- if os.path.isfile(config):
- config_content = open(config).read()
- else:
- config_content = config
-
- try:
- self._config = json.loads(config_content)
- except Exception as e:
- raise e
-
-
- def __getattr__(self, attr):
- if attr in self._config:
- if isinstance(self._config[attr], dict):
- return DictNodeWrapper(self._config[attr])
- else:
- return self._config[attr]
- return None
-
- def __getitem__(self, attr):
- return self.__getattr__(attr)
-
- def __contains__(self, item):
- return (item in self._config)
-
- def __str__(self):
- return json.dumps(self._config, indent=4)
-
- repr = __str__
-
- if __name__ == '__main__':
- config = Config()
- print(config)
- print("input_data_path" in config)
|