Config file with a .py file

守給你的承諾、 提交于 2019-12-20 04:34:10

问题


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.SOUNDENABLED == 1:
    ....

f = open(configfile.FILEPATH, 'a')
...

This is confirmed by the fact that many people use INI files for local configuration with ConfigParser module or iniparse or other similar modules.

Question:

Why would using an INI file for local configuration + an INI parser Python module be better than just importing a configfile.py file containing the right config values as constants?


回答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).




回答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?




回答3:


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




回答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.



来源:https://stackoverflow.com/questions/40930663/config-file-with-a-py-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!