- The first time a module is imported, an entry for it is made in
sys.modules
.sys.modules
is a dict, mapping the module name to the module code. All subsequent imports of the same module find the module’s name insys.modules
, and simply retrieve the module’s code from thesys.modules
dict. So the code in the module is executed only once, the first time it’s imported. That’s why no error results from importingcf
from withincf
. - You didn’t explain exactly what you did with IDLE. My guess: you had
cf.py
open in an IDLE window, and did “Run Module” (F5) in that window. Fine. Then IDLE ran the code in the file. That’s not the same as importingcf
: it’s running the code incf
directly. Part of running that code is importingcf
, which printscf.a
. Another part of running that code is – again! – printingcf.a
. That’s why you saw it twice.
By the way, I don’t know what you mean by “and in the console 1 times”. But, again, you didn’t explain exactly what you did. When I run cf.py
from a console, I see 1
two times, and for the same reason I just explained:
$ python cf.py
1
1
1
solved Importing a module in the module [closed]