If you import yourself in Python, why don't yo

2019-06-20 01:38发布

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?

5条回答
神经病院院长
2楼-- · 2019-06-20 02:02

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

查看更多
beautiful°
3楼-- · 2019-06-20 02:15

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

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-06-20 02:18

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.

查看更多
走好不送
5楼-- · 2019-06-20 02:19

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.

查看更多
The star\"
6楼-- · 2019-06-20 02:21

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

查看更多
登录 后发表回答