为什么不能在Python中重新导入? [英] Why can't you re-import in Python?

查看:159
本文介绍了为什么不能在Python中重新导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于SO上的重新导入有很多问题和答案,但如果不了解其背后的机制,这一切似乎都非常直观。

There are plenty of questions and answers regarding re-imports on SO, but it all seems very counter-intuitive without knowing the mechanisms behind it.

如果导入一个模块,更改内容,然后尝试再次导入它,你会发现第二次导入没有效果:

If you import a module, change the contents, then try to import it again, you'll find that the second import has no effect:

>>> import foo    # foo.py contains: bar = 'original'
>>> print foo.bar
original
>>> # edit foo.py and change to: bar = 'changed'
>>> import foo
>>> print foo.bar
original

当我发现<$ c时,我是一个非常开心的露营者$ c>重新加载:

>>> reload(foo)
>>> print foo.bar
changed

但是当您从以下位置导入项目时,没有简单的解决方案没有导入模块本身的模块:

However there's no easy solution when you're importing items from a module without importing the module itself:

>>> from foo import baz
>>> print baz
original
>>> # change foo.py from baz = 'original' to baz = 'changed'
>>> from foo import baz
>>> print baz
original
>>> reload(foo)
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    reload(foo)
NameError: name 'foo' is not defined

当你给它一个新的 import 语句时,为什么Python不会更新导入的项目?

Why won't Python update imported items when you give it a new import statement?

推荐答案

导入模块时,它缓存在 sys.modules中 。在同一会话中再次导入同一模块的任何尝试都只返回其中包含的现有模块。当从多个位置导入模块时,这可以加快整体体验。它还允许模块在所有导入之间共享自己的对象,因为每次都返回相同的模块。

When you import a module, it is cached in sys.modules. Any attempt to import the same module again within the same session simply returns the already existing module contained there. This speeds up the overall experience when a module is imported from multiple places. It also allows a module to have its own objects shared between all of the imports, since the same module is returned each time.

如上所述,你可以使用 重新加载 以重新导入整个模块。检查文档中的注意事项,因为即使这不是万无一失的。

As mentioned you can use reload to re-import a whole module. Check the documentation for the caveats, because even this is not fool-proof.

当您从模块导入特定项目时,整个模块将按上述方式导入,然后您请求的对象放在您的命名空间中。 reload 不起作用,因为这些对象不是模块,并且您从未收到对模块本身的引用。解决方法是获取模块的引用,重新加载,然后重新导入:

When you import specific items from a module, the whole module is imported as above and then the objects you requested are placed in your namespace. reload doesn't work because these objects aren't modules, and you never received a reference to the module itself. The work-around is to get a reference to the module, reload it, then re-import:

>>> from foo import baz
>>> print baz
original
>>> # change foo.py from baz = 'original' to baz = 'changed'
>>> import foo
>>> reload(foo)
>>> from foo import baz
>>> print baz
changed

这篇关于为什么不能在Python中重新导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆