If you import yourself in Python, why don't you get an infinite loop?
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 i开发者_高级运维nfinite loop?
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
When Python encounters an import
statement, it checks sys.modules
for the presence of the module first before doing anything
import module
does not reload the module if it has already been imported
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.
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.
精彩评论