Python模块覆盖双下划线

标签 python django

有谁知道为什么我的 __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 the import 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/

相关文章:

python - 按下按键时 pygame 继续循环

python - python中的数据可视化——连接到数据库后

django - 从 Django 的 ArrayAgg 中排除空值

django - 如何对每个项目单独进行访问计数

python - 如何解决TypeError : 'float' object is not iterable

python - 如何通过解析导入来组合并获取单个 Python 文件

python - Ctypes将float传递给函数返回随机数

python - 为什么 Django 看不到我的静态文件?

django - 在 Django 表单上为 DatetimeInput 输入有效的日期/时间

Django-Rest-Framework 3.0 字段名 '<field>' 对模型 `ModelBase` 无效