What is significance of __name__ in python

In python modules can be loaded by importing in some other module or executed directly as standalone program. So, how does python detect at run time that a particular module was imported  or it was executed directly as standalone application.
Simple answer is : using system defined variable __name__.

When a module is imported  __name__ variable contains module name.However, __name__ contains __main__ if executed directly.

Illustration:-
Create a file name "parentmodule.py" with following code lines.
def importedmodule():
    print "I have been imported."

def directexecution():
    print "I have run as application."
    
#Executed directly as application
if __name__ == '__main__':
    directexecution()
else:
    importedmodule()

Create another file "test.py" with following code lines

import parentmodule

def importedmodule():
    print "I have been imported."

def directexecution():
    print "I have run as application."
    
Now run parentmodule.py directly, it will call method directexecution(). However, if we run test.py - importedmodule() method is executed, because parentmodule has been imported in test.py so __name__ is not equal to __main__.

Sample output:-
C:\Python27\pgm>python parentmodule.py
I have run as application.

C:\Python27\pgm>python test.py
I have been imported.

1 Comments

Previous Post Next Post