python - 重新加载模块是否会更改先前导入/重新加载的模块中的名称?

标签 python

我有一个名为 myfile.py 的模块

    //myfile.py
    msg = 'Hello World'

然后我导入它:import myfile

然后我做一些修改,比如:

    //myfile.py (updated)
    a = 'Some text'
    b = 'Some other text'

然后我调用重新加载函数:

    from imp import reload
    reload(myfile)

现在当我运行:dir(myfile) 它显示当前模块重新加载的名称以及以前的(所有其他以前的导入/重新加载)

这是否意味着在导入/重新加载模块时,“所有”名称(甚至更新后省略的名称)都可单独用于外部世界?

最佳答案

来自imp.reload documentation :

When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains.

模块在重新加载之前不会被删除。模块的新代码在所有旧变量绑定(bind)仍然存在的情况下执行。新代码定义的任何名称都会替换旧绑定(bind),但新版本未定义的任何名称都保留其旧值。 This also applies in Python 2 .

关于python - 重新加载模块是否会更改先前导入/重新加载的模块中的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21965009/

相关文章:

python - 如何在django中利用浏览器缓存

python - 根据任意字段查找字典列表的交集

python - SQLAlchemy 连接如何与基于 session 的事务相关?

python - 更正用户消息中的重复字母

python - 使用 setup.py 链接 library.lib

python - 在Python中执行多线程程序以单线程运行

python - 循环中的唯一值数组

python - 将字符串(任意顺序)与大数组中的字符串进行匹配

Python list 2 项目符号形式的列表

python 请求不适用于来自 apache 和 wsgi 的 https