首先,场景。我有一个模块 config.py:
DEBUG = False # Set to True with --debug option
另一个模块 do.py 使用它:
from config import DEBUG
def do_something():
if DEBUG:
print 'Debug...'
print 'do something'
在 main.py 中:
import config
import do
import sys
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == '--debug':
config.DEBUG = True
do.do_something()
现在,当我运行它时:
$ python2.7 main.py --debug
do something
因此,在 do_something()
中,DEBUG
为 False。
拥有这样的配置标志的最佳方式是什么:
- 有效,
- 简洁,并且
- 安全吗?
最佳答案
针对第1点,我可以这样编写do.py:
import config
def do_something():
if config.DEBUG:
print 'Debug...'
print 'do something'
但现在 config.DEBUG
不再那么简洁(第 2 点)。
或者我可以这样编写 config.py:
class Debug(object):
_DEBUG = False
def __call__(self):
return self._DEBUG
def set(self, debug):
self._DEBUG = debug
DEBUG = Debug()
但这允许出现像这样的简单错误:
>>> import config
>>> config.DEBUG()
False
>>> from config import DEBUG
>>> DEBUG()
False
>>> DEBUG.set(True)
>>> DEBUG()
True
>>> DEBUG.set(False)
>>> DEBUG()
False
>>> if DEBUG: print 'Oops'
...
Oops
这违反了第 3 点。
那么有没有更好的解决方案呢?
关于python - 有没有更好的方法从 Python 模块导入变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30364569/