Issue
I am new to Python and I am trying to create a class that handles loading my config values. So far this is what I have :
import os, json
class ConfigHandler:
CONFIG_FILE = "/config.json"
def __init__(self):
print("init config")
if os.path.exists(self.CONFIG_FILE):
print("Loading config file")
self.__dict__ = json.load(open(self.CONFIG_FILE))
else:
print("Config file not loaded")
Then in my main application class, I am doing :
from ConfigHandler import ConfigHandler
class MainApp:
config = ???
I have tried several ways to get the ConfigHandler to initialize, but it never hits the print statements. And I am not sure how to call the confighandler to get the dictionary. Any help is appreciated!
Solution
Given config.json
in the root of your drive if using CONFIG_FILE = "/config.json"
:
{
"a": 1,
"b": 2,
"c": "Mark"
}
Then:
from ConfigHandler import ConfigHandler
config = ConfigHandler() # Create an instance...calls __init__ implictly
print(config.a, config.b, config.c)
Will output:
1 2 Mark
Answered By - Mark Tolonen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.