[Solved] Importing a module in the module [closed]


  1. 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 in sys.modules, and simply retrieve the module’s code from the sys.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 importing cf from within cf.
  2. 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 importing cf: it’s running the code in cf directly. Part of running that code is importing cf, which prints cf.a. Another part of running that code is – again! – printing cf.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]