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!
2
Answers
Given
config.json
in the root of your drive if usingCONFIG_FILE = "/config.json"
:Then:
Will output:
Configure your object with a
dict
, and provide a separate class method for obtaining thatdict
from a JSON file.Note, too, that the caller should be responsible for opening the file, not your
ConfigHandler
class.