带有.py文件的配置文件 [英] Config file with a .py file

查看:91
本文介绍了带有.py文件的配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人告诉我这样做会是不太好的做法:

I have been told that doing this would be a not-very-good practice:

SOUNDENABLED = 1
FILEPATH = 'D:\\TEMP\\hello.txt'

main.py

import configfile

if configfile.SOUNDENABLED == 1:
    ....

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

以下事实证实了这一点:许多人使用INI文件进行 ConfigParser进行本地配置模块或 iniparse 或其他类似模块.

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

为什么使用INI文件进行本地配置+ INI解析器Python模块会比仅导入包含正确的配置值作为常量的configfile.py文件更好?

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?

推荐答案

此处唯一需要关注的是.py可以具有任意Python代码,因此它有可能以任意方式破坏程序.

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

这篇关于带有.py文件的配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆