Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python configuration file: Any file format recommendation? INI format still appropriate? Seems quite old school

Tags:

python

I need to store configurations (key/value) for a Python application and I am searching for the best way to store these configurations in a file.

I run into Python's ConfigParser and I wondered if the INI file format is really still appropriate nowadays?! Does there exist a more up-to-date format or is INI still the recommended way to go? (XML, JSON, ...)

Please share your opinions/recommendations...

like image 807
gecco Avatar asked Nov 22 '11 11:11

gecco


People also ask

How do I configure a file in Python?

Python can have config files with all settings needed by the application dynamically or periodically. Python config files have the extension as . ini. We'll use VS Code (Visual Studio Code) to create a main method that uses config file to read the configurations and then print on the console.

How do you write an INI file in Python?

To read and write INI files, we can use the configparser module. This module is a part of Python's standard library and is built for managing INI files found in Microsoft Windows. This module has a class ConfigParser containing all the utilities to play around with INI files.

What is INI file in Python?

The python's configparser module used to read the . ini files, typically these file contains configuration information. The following few examples illustrate some of the more interesting features of the ConfigParser module.


1 Answers

Consider using plain Python files as configuration files.

An example (config.py):

# use normal python comments  value1 = 32 value2 = "A string value"  value3 = ["lists", "are", "handy"] value4 = {"and": "so", "are": "dictionaries"} 

In your program, load the config file using exec (docs):

from pathlib import Path  if __name__ == "__main__":     config = {}     exec(Path("config.py").read_text(encoding="utf8"), {}, config)          print(config["value1"])     print(config["value4"]) 

I like this approach, for the following reasons:

  • In the simple case, the format is as easy to author as an INI-style config file. It also shares an important characteristic with INI files: it is very suitable for version control (this is less true for XML and maybe also for JSON)
  • I like the flexibility that comes with having the config file in an actual programming language.

The approach is widely used, a few examples:

  • A Django site's settings lives inside settings.py. Django does not use execfile, it uses import to read/execute settings.py AFAIK, but the end result is the same: the code inside the settings file is executed.
  • The bash shell reads and executes ~/.bashrc on startup.
  • The Python interpreter imports site.py on startup.
like image 116
codeape Avatar answered Sep 19 '22 21:09

codeape