skip to Main Content

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


  1. 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
    
    Login or Signup to reply.
  2. Configure your object with a dict, and provide a separate class method for obtaining that dict from a JSON file.

    class ConfigHandler:    
        def __init__(self, d):
            self.__dict__ = d
    
        @classmethod
        def from_json(cls, fh):
            return cls(json.load(fh))
    

    Note, too, that the caller should be responsible for opening the file, not your ConfigHandler class.

    with open("config.json") as f:
        c = ConfigHandler.from_json(f)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search