Search code examples
pythonconfigparser

Best practice to use Python configparser module and get values?


I code a simple Python project and I want to use configparser module to get values from config.ini file.

I did it in this way:

#!/usr/bin/env python3

import configparser
import os
import sys

class ConfigReader(object):

    def __init__(self, base_path):
        self.__config_path = os.path.join(base_path, 'config', 'config.ini')
        if os.path.exists(self.__config_path):
            self.config = configparser.ConfigParser()
            self.config.read(self.__config_path)
        else:
            raise FileNotFoundError(
                'Config file is NOT present as "' + self.__config_path + '" !')

    def get_mac_chrome_driver(self):
        return self.config['mac']['chrome_driver_path']

    def get_win_chrome_driver(self):
        return self.config['win']['chrome_driver_path']

But, now the problem is I have to new an ConfigReader object everytime, then I can use the get_mac_chrome_driver() function(to get value of config['mac']['chrome_driver_path']).

I believe it is not the best practice and is not pythonic.

May I just use it by from utls.ConfigReader import CHROME_DRIVER_PATH?

Thanks!


Solution

  • After reading Django source code, it might be more 'pythonic' to just write the parameters/values in a settings.py, see https://github.com/django/django/blob/master/django/conf/global_settings.py