name==main in python

if __name__ == ‘__main__’

Welcome to another chapter of our Python tutorial series, Learn Python with me. In the previous post, we discussed how we could import another program as a module, and in this post, we will discuss how to check if you are getting output from a module or a program using if __name__ == ‘__main__’:.

For every program executed in Python, an internal variable ‘__name__’ is created. It is responsible for letting us know if a program is run as a module or a program.

Whenever you run a program as a program, this variable ‘__name__’ would have the value ‘__main__’ stored in it. However, when the same program is run as a module in another program, this variable ‘__name__’ would not have the value ‘__main__’.

Based on the explanation above, you can easily create a logic using ‘if condition block’ to check if you are running a program as a module or an individual program. Let us look at the examples below.

firstprogram.py

#a program in python to display a message
#save this program as firstprogram.py

def display():
    print("Hello World!")

if __name__ == '__main__':
    display()
    print("This is run as a program")
else:
    print("This is run as a module")

secondprogram.py

#save this program as secondprogram.py

"""
In this program, we import firstprogram.py
as a module.
"""

import firstprogram

firstprogram.display()

Please note that I have saved both files in the same directory for this illustration.

Output

PS C:\Python_practise> python firstprogram.py
Hello World!
This is run as a program
PS C:\Python_practise> python secondprogram.py
This is run as a module
Hello World!

if __name__ == ‘__main__’

  • When the firstprogram.py is run as an individual program, the variable ‘__name__’ would have the value ‘__main__’ and that’s why since the ‘if condition’ is satisfied, the print statement, “This is run as a program” gets displayed in the output.
  • However, when we imported firstprogram.py as a module in the secondprogram.py and tried running the display function of firstprogram.py from the secondprogram.py, the print statement in the else block “This is run as a module” gets displayed. The ‘__name__’ would not have the value ‘__main__’ in cases when a program is imported as a module in another program.

This concept will be beneficial when you work with scenarios using Django framework, etc., or when you import a module or a package into your program.

Scroll to Top