views:

165

answers:

5

This question is a response to the following SO post:

http://stackoverflow.com/questions/3558718/how-do-i-pickle-an-object/3558783#3558783

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?

+2  A: 

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

Eton B.
+9  A: 

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

carl
+1: Quote from Manual. Very helpful.
S.Lott
+2  A: 

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.

recursive
+4  A: 

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

chryss
+2  A: 

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.

abhin4v
First and only answer talking about namespaces.
Beau Martínez