有谁知道为什么我的 __status__
字符串不会打印出来?我得到一个 NameError
。但是,如果我设置它(它会覆盖),我可以打印 CAT。
所以我不能使用双下划线,因为它现在是模块 settings_local 的神奇属性?
settings.py
__status__ = "Base"
CAT = 5
try:
# This will work if a settings_local.py exists
from settings_local import *
except ImportError as e:
print "Add a settings_local blah blah"
sys.exit()
print __status__ # returns Base
print CAT # Returns 1
print settings_local.__status__ # Returns NameError
settings_local.py
__status__ = "Development"
CAT = 1
我应该只在 settings_local.py 中执行此操作吗?
status = __status__
然后就这样使用它?
最佳答案
from <module> import *
如果目标模块没有 __all__
,则语法 忽略 以下划线开头的名称属性(如果只导入该属性中列出的名称)。来自 import
statement documentation :
If the list of identifiers is replaced by a star (
'*'
), all public names defined in the module are bound in the local namespace of theimport
statement.The public names defined by a module are determined by checking the module’s namespace for a variable named
__all__
; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in__all__
are all considered public and are required to exist. If__all__
is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_'
).
(大胆强调我的)。
此外,您没有导入 settings_local
模块本身; NameError
是抛出,因为你没有导入模块,只导入模块中包含的属性。这有效:
import settings_local
print settings_local.__status__
您的其他选择是:
两个导入语句:
from settings_local import * try: from settings_local import __status__ except ImportError: # no __status__ defined in the local settings pass
添加
__all__
列出您的settings_local.py
模块:__all__ = ['CAT', '__status__'] __status__ = "Development" CAT = 1
请注意 Python advises against creating new __*__
names :
Any
use of__*__
names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.
关于Python模块覆盖双下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26789281/