python - 有没有更好的方法从 Python 模块导入变量?

标签 python import module

首先,场景。我有一个模块 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() 中,DEBUGFalse

拥有这样的配置标志的最佳方式是什么:

  1. 有效,
  2. 简洁,并且
  3. 安全吗?

最佳答案

针对第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/

相关文章:

python - 是否有可以发现此类错误的工具?

Python selenium 从下拉列表中选择第一个元素

c - 解析PIMAGE_IMPORT_DESCRIPTOR时手动加载PE导入结果错误

Drupal Facebook 连接功能

php - SilverStripe - 将 CheckboxsetField 与 MultiForm 模块结合使用

python - 如何在pytorch中运行一批?

python - 如何在keras中的LSTM自动编码器中获取middel层的输出

java - PDFBox如何从另一个pdf导入acrofield

objective-c - 从 Swift 访问 Objective-C 变量/函数

module - TypeScript:使用类作为模块