Usually my project directory structure look like:
project_name/
lib/
utils.py
logs/
main.py
requirements.txt
config.json
My config.json file looks like:
{
"api": {
"api_key": "abcdefg",
"api_secret": "hijklmn"
},
"trading": {
"invest_amount": 50,
"mode": "futures",
"cumulative_position": false
}
}
In utils.py, I have a class Config
import typing
import inspect
import os
import json
from typing import Any
class Config(object):
_CONFIG_FILE: typing.Optional[str] = None
_CONFIG: typing.Optional[dict] = None
def __init__(self):
config_file = Config.get_config_path(frame=inspect.stack()[1])
with open(config_file, 'r') as f:
Config._CONFIG = json.load(f)
@staticmethod
def get_config_path(frame: inspect.FrameInfo, config_file_name: str = "config.json") -> str:
caller_file_name = frame[0].f_code.co_filename
caller_folder_name = os.path.dirname(caller_file_name)
config_file_name = os.path.join(caller_folder_name, config_file_name)
return config_file_name
@staticmethod
def get_config_value(param: str) -> Any:
for key in Config._CONFIG.keys():
value = Config._CONFIG.get(key).get(param, None)
if value is not None:
return value
raise ValueError(f"{param} doesn't exist")
And I will use it in main.py usually:
from lib.utils import Config
def main(trading_mode, invest_amount, cumulative_position):
print(trading_mode, invest_amount, cumulative_position)
if __name__ == "__main__":
config = Config()
main(trading_mode=config.get_config_value(param="mode"),
invest_amount=config.get_config_value(param="invest_amount"),
cumulative_position=config.get_config_value(param="cumulative_position"))
Is there any code that can improve or rewrite in class Config
, for the purpose of efficiency, readability or clear logic, etc?
dict
returned byjson.load()
. \$\endgroup\$with open("config.json", "r")
? How should I store the desired values and input these intomain()
? Should I constructure a function likeconfig.get_config_value
for this? \$\endgroup\$dict
to a variableconfig
any different from assigning an instance ofConfig
to such a variable? And given your config is a dict, you can just usecofig.get(key)
instead ofconfig.get_config_value(key)
. \$\endgroup\$class Config
or usingconfig.get(key)
? It's a bit confusing for me to understand the words, better in answer the question instead of comment, it would be helpful, many thanks! \$\endgroup\$