Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a settings file in a Python program

A "settings file" would be a file where things like "background color", "speed of execution", "number of x's" are defined. Currently, I implemented it as a single setting.py file, which I import in the beginning. Someone told me I should make it a settings.ini file instead, but I don't see why! Care to clarify, what is the optimal option?

like image 771
corazza Avatar asked Sep 03 '26 10:09

corazza


1 Answers

There is no optimal solution; it is a matter of preference.*

Normally, settings do not need to be expressed in a Turing-complete language: they're often just a bunch of flags and options, sometimes strings and numbers, etc. An argument for having a settings.py file (though very unorthodox) would be if the end-user was expected to write code to generate very esoteric configurations (e.g. maps for a game). This would then be fairly similar to shell script .bashrc-style files.

But again, in 99.9% of programs, the settings are often just a bunch of flags and options, sometimes strings and numbers, etc. It's fine to store them as JSON or XML. It also makes it easy to perform reflection on your settings: for example, automatically listing them in a tree manner, or automatically creating a GUI out of the descriptions.

(Also it may be a (unlikely?) security issue if you allow people to inject code by modifying the settings file.)

*edit: no pun intended...

like image 151
ninjagecko Avatar answered Sep 06 '26 02:09

ninjagecko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!