如果你在Python中导入自己,为什么不会出现无限循环呢?

发布于 2024-09-15 10:56:47 字数 202 浏览 5 评论 0原文

这个问题是对以下SO帖子的回应:

How do I pickle对象?

在该线程中,OP 意外地在同一模块的顶部导入了自己的模块。为什么这不会导致无限循环?

This question is a response to the following SO post:

How do I pickle an object?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

你的他你的她 2024-09-22 10:56:47

模块仅导入一次。 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

混吃等死 2024-09-22 10:56:47

当 Python 遇到 import 语句时,它会在执行任何操作之前先检查 sys.modules 是否存在该模块

When Python encounters an import statement, it checks sys.modules for the presence of the module first before doing anything

嘴硬脾气大 2024-09-22 10:56:47

如果模块已经导入,导入模块不会重新加载模块

import module does not reload the module if it has already been imported

八巷 2024-09-22 10:56:47

我相信 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.

烟燃烟灭 2024-09-22 10:56:47

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.

旧话新听 2024-09-22 10:56:47

出于好奇,我使用以下代码获得了无限循环(或者更确切地说是最大递归深度):

# test_file.py

print('beep')

# Passing the first instance of 'test_file' with __name__ == '__main__'
if __name__ == 'test_file':
    import sys
    del sys.modules['test_file']

import test_file

For the sake of curiosity, I got an infinite loop (or rather a maximum recursion depth one) with this code:

# test_file.py

print('beep')

# Passing the first instance of 'test_file' with __name__ == '__main__'
if __name__ == 'test_file':
    import sys
    del sys.modules['test_file']

import test_file
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文