Skip to content Skip to sidebar Skip to footer

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

Solution 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

Solution 2:

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

Solution 3:

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

Solution 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.

Solution 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.

Post a Comment for "If You Import Yourself In Python, Why Don't You Get An Infinite Loop?"