DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht

If __name__ == '__main__' in Python

  • 3 minutes read
If __name__ == '__main__' in Python

    Table of Contents

What does if __name__ == ‘__main__‘in python means?

In python, you must have come accross the following code :-

if __name__ == '__main__':

In this tutorial, we will learn in detail what does the above statement means. As per official documentation:

‘__main__‘ is the name of the scope in which top-level code executes. A module‚Äôs __name__ is set equal to ‘__main__‘ when read from standard input, a script, or from an interactive prompt.

It means that if any module/python file is running as the main program, it sets the special__name__ variable to have a value ‘__main__‘

Create a python file ‘’ and type the following code:-


print f'The name of module one is {__name__}' 

If you will run it. You will get the following output:-

The name of module one is __main__

However, if this module is imported in some other file or module, variable __name-- will be set as the name of the first module.

To make it clear, create another python file (module) called ‘’ and import first module in it:-


import module_one

Since, we have imported module_one in, when we will run the second module, it will execute the first module and we will get the following output on running

The name of module one is module_one

Since, now we are directly running, Python will set it’s __name__ as ‘__main__‘


import module_one

print f'The name of module two is {__name__}' 

Output of this module will be:-

The name of module one is module_one
The name of module two is __main__

Hence if __name__ == ‘__main__‘ checks whether the file is being run directly or it has been imported into some other file. The following example will make it more clear:-


print "This will always be printed"

if __name__ == "__main__": 
    print "Module one has been run directly"
    print "Module one has been imported"
# Output
This will always be printed
Module one has been run directly

Now if we just import module_one in and run it, we will get the following output.

import module_one
# Output
This will always be printed
Module one has been imported

We use this if we want to make a certain function run, when a module is run directly and some other function to run if it is imported.

If you have any query, please feel free to ask in comment section.

Related Posts

Matplotlib Tutorial in Python | Chapter 2 | Extracting Data from CSVs and plotting Bar Charts.
By Udit Vashisht

Matplotlib Tutorial in Python

Chapter 2 | Extracting Data from CSVs and plotting Bar Charts

In the last chapter, we learned to draw simple plots in Matplotlib and further customizing it.In this chapter we will be learning to extract data from external sources like CSV and creating ...

Read More
How to append to a list in Python ? - Python List append() method
By Udit Vashisht

Python List append() method

The Python list append() method adds an item to the end of the list. The length of the list increase by one.

Syntax of append()

The syntax for the same is :-


Parameters of append()

The method takes only a single argument


Read More
How to create a Telegram Bot using Python?
By Udit Vashisht

Create a Telegram Bot using Python

In this article, we will learn to create a simple telegram bot using python. First of all, we will create the API token for our telegram bot.

Connect with FatherBot

We can do this by opening the BotFather bot on telegram. Yes, we ...

Read More
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python