If you import yourself into Python, why don't you get an infinite loop?

This question is an answer to the following SO post:

How to saw an object?

In this thread, the OP randomly imports its own module at the top of the same module. Why doesn't this cause an endless loop?

+6
python import infinite-loop
source share
5 answers

Modules are imported only once. Python understands that it is already imported, so it does not do it again.

See: http://docs.python.org/tutorial/modules.html#more-on-modules

+10
source share

When Python encounters an import statement, it checks sys.modules for a module before doing anything.

+4
source share

import module does not reload the module if it is already imported

+2
source share

I believe that python tracks are already imported, so that time is not wasted, excess import. Each module can be imported only once.

+2
source share

Importing in Python causes the namespace bindings for the imported module to fit into the current namespace if they are not already present. If you import a module twice, it will actually be imported (and therefore executed) only once. Therefore, when you import a module into yourself, nothing happens because the namespace bindings are already present in the current namespace.

+2
source share

All Articles