0

There are multiple posts discussing whether this is recommended, but lets suppose you want to do a config.py for your python app. Is there any difference between the two (similar to me) approaches below:

  • 1). make the module as an ini file and then parse it with exec(Path())

Like the following example, taken from here:

## config.py ##

value1 = 32
value2 = "A string value"

value3 = ["lists", "are", "handy"]
value4 = {"and": "so", "are": "dictionaries"}

and then

from pathlib import Path

if __name__ == "__main__":
    config = {}
    exec(Path("config.py").read_text(encoding="utf8"), {}, config)
    
    print config["value1"]
    print config["value4"]
  • 2). write a module with just a dictionary with the settings and then import the module:

Hence:

## config.py ##

DEFAULT = {
    value1: 32,
    value2: "A string value",

    value3: ["lists", "are", "handy"],
    value4 : {"and": "so", "are": "dictionaries"},
}

and then

import config.py

if __name__ == "__main__":
    cfg = config.DEFAULT
    
    print cfg["value1"]
    print cfg["value4"]
Aenaon
  • 3,169
  • 4
  • 32
  • 60
  • The second one is surely better than simply executing a file with no input control over it... But why not just have a `config.ini` and read with the built-in [`configparser`](https://docs.python.org/3/library/configparser.html#module-configparser)? – Tomerikoo Feb 01 '21 at 14:02

1 Answers1

0

You can do both these approaches but as Tomerikoo explain, there is both an advantage and disadvantage in your config being a code:

Advantage: It is elegant (especially your second way) and you can easily execute some dynamical setting or similar because your config is code.

Disadvantage: If you don't have control over the config, someone can execute the code he is not supposed to execute. Also things can go more bad for this reason.

ConfigParser is the preferred way how to do this unless your config is more of a script than just a plain key-value based config.

Roman Pavelka
  • 3,736
  • 2
  • 11
  • 28