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

2019-06-20 01:27发布

问题:

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?

回答1:

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



回答2:

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



回答3:

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



回答4:

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.



回答5:

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.