Search code examples
pythonjsonconfigurationyaml

What is the best method for setting up a config file in Python


I realise this question as been asked before (What's the best practice using a settings file in Python?) but seeing as this was asked 7 years ago, I feel it is valid to discuss again seeing as how technologies have evolved.

I have a python project that requires different configurations to be used based on the value of an environment variable. Since making use of the environment variable to choose a config file is simple enough, my question is as follows:

What format is seen as the best practice in the software industry for setting up a configuration file in python, when multiple configurations are needed based on the environment?

I realise that python comes with a ConfigParser module but I was wondering if it might be better to use a format such as YAML or JSON because of there raise in popularity due to their ease of use across languages. Which format is seen as easier to maintain when you have multiple configurations?


Solution

  • If you really want to use an environment-based YAML configuration, you could do so like this:

    config.py

    import yaml
    import os
    
    config = None
    
    filename = os.getenv('env', 'default').lower()
    script_dir = os.path.dirname(__file__)
    abs_file_path = os.path.join(script_dir, filename)
    with open(abs_file_path, 'r') as stream:
        try:
            config = yaml.load(stream)
        except yaml.YAMLError as exc:
            print(exc)