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.
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.