如果你在Python中导入自己,为什么不会出现无限循环呢?
This question is a response to the following SO post:
In that thread, the OP accidentally imports his own module at the top of the same module. Why doesn't this cause an infinite loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
模块仅导入一次。 Python 意识到它已经被导入,所以不再这样做。
请参阅:http://docs.python.org/tutorial/modules.html #更多模块
Modules are imported only once. Python realizes it already has been imported, so does not do it again.
See: http://docs.python.org/tutorial/modules.html#more-on-modules
当 Python 遇到
import
语句时,它会在执行任何操作之前先检查sys.modules
是否存在该模块When Python encounters an
import
statement, it checkssys.modules
for the presence of the module first before doing anything如果模块已经导入,
导入模块
不会重新加载模块import module
does not reload the module if it has already been imported我相信 python 会跟踪哪些模块已经被导入,这样时间就不会浪费在多余的导入上。每个模块只能导入一次。
I believe python tracks which modules have already been imported so that time is not wasted redundantly importing. Each module can only be imported once.
Python 中的导入会导致导入模块的命名空间绑定放入当前命名空间(如果它们尚不存在)。如果您导入一个模块两次,它实际上只会被导入(并因此执行)一次。这就是为什么当您将模块导入自身时,实际上什么也没有发生,因为命名空间绑定已经存在于当前命名空间中。
An import in Python causes the namespace bindings for the imported module to be put in the current namespace if they are not present already. If you import a module twice, it will actually be imported (and hence executed) only once. That is why when you import the module into itself, nothing actually happens as the namespace bindings are already present in the current namespace.
出于好奇,我使用以下代码获得了无限循环(或者更确切地说是最大递归深度):
For the sake of curiosity, I got an infinite loop (or rather a maximum recursion depth one) with this code: