Skip to content Skip to sidebar Skip to footer

Config File With A .py File

I have been told that doing this would be a not-very-good practice: configfile.py SOUNDENABLED = 1 FILEPATH = 'D:\\TEMP\\hello.txt' main.py import configfile if configfile.SOUNDE

Solution 1:

The only concern here is that a .py can have arbitrary Python code, so it has a potential to break your program in arbitrary ways.

If you can trust your users to use it responsibly, there's nothing wrong with this setup. If fact, at one of my previous occupations, we were doing just that, without any problems that I'm aware of. Just on the contrary: it allowed users to eliminate duplication by autogenerating repetitive parts and importing other config files.

Another concern is if you have many files, the configuration ones are better be separated from regular code ones, so users know which files they are supposed to be able to edit (the above link addresses this, too).


Solution 2:

Importing a module executes any code that it contains. Nothing restricts your configfile.py to containing only definitions. Down the line, this is a recipe for security concerns and obscure errors. Also, you are bound to Python's module search path for finding the configuration file. What if you want to place the configuration file somewhere else, or if there is a name conflict?


Solution 3:

This is a perfectly acceptable practice. Some examples of well-known projects using this method are Django and gunicorn.


Solution 4:

It could be better for some reasons

  1. The only extension that config file could have is py.
  2. You cannot distribute your program with configs in separate directory unless you put an __init__.py into this directory
  3. Nasty users of your program can put any python script in config and do bad things.

For example, the YouCompleteMe autocompletion engine stores config in python module, .ycm_extra_conf.py. By default, each time config is imported, it asks you, whether you sure that the file is safe to be executed.

  1. How would you change configuration without restarting your app?

Generally, allowing execution of code that came from somewhere outside is a vulnerability, that could lead to very serious consequences.

However, if you don't care about these, for example, you are developing web application that executes only on your server, this is an acceptable practice to put configuration into python module. Django does so.


Post a Comment for "Config File With A .py File"