0

main.py

#main.py
import main
print('Hello')

Output:

Hello
Hello

I believe that when it comes to the line import main, at that time, main is registered in sys.modules and hence the import statement of another script - which I believe, is not a part of __main__ - is not executed. Can someone please tell me whether I understand it correctly? If not, please give an explanation.

3 Answers3

6

Let's add a little debugging output:

import sys
print([key for key in sys.modules.keys() if 'main' in key])
import main

It prints:

['__main__']
['__main__', 'main']

Why is that?

If you run a module it will not be added as its modules name to sys.modules. Instead it will always be __main__.

If you then import the module by its name (main). That name is not present in sys.modules and as the result the module will be imported again, its code executed and the modules stored in sys.modules under its name.

On executing main.py it will print ['__main__'] and on the re-import it will print both module names: ['__main__', 'main'].

This implies one rule: try not to import the module you are running anywhere in your code.

Klaus D.
  • 13,874
  • 5
  • 41
  • 48
1

It only prints it twice because a module is only actually loaded once. This prevents possible unbound recursion. So your print statement gets executed once by the imported module and once by the main program.

Mario Camilleri
  • 1,457
  • 11
  • 24
0

Since you're importing main inside main the print statement is executed twice,thats how python works

Maghil vannan
  • 435
  • 2
  • 6
  • 19