Python module with name __main__.py doesn't run while imported

Advertisements

Somebody asked me a question and I honestly didn’t try it before, So it was interesting to know what exactly happens when we name a module __main__.py. So I named a module __main__.py, imported it in another file with name test.py. Surprisingly when I tried to run test.py it prints nothing and none of the functions of __main__.py are available in test.py. Here is the contents of these files :

Here is the contents of __main__.py :

def add(a,b):
    result = a+b
    return result

print(__name__)

if __name__=='__main__':
    print(add(1,2))

Here is the contents of test.py :

import __main__

Why isn’t the print statement from __main__.py reached? Although when I rename the __main__.py with some other name such as func.py, the program runs correctly and the line that prints module’s name works fine.

>Solution :

When you run python test.py, the test.py module itself is already present in sys.modules with the key "__main__" (see top-level code environment in the docs). The import __main__ will just return this existing cache hit, so the presence of a __main__.py file on sys.path is irrelevant.

These modifications to test.py will prove that point:

import sys
print(sys.modules['__main__'])  # it's already in there before the import
import __main__
print(__main__.__file__)  # this should be the abspath of test.py

Leave a ReplyCancel reply