What is if __name__ == “__main__” ??


Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!


Every module in python has a special attribute called __name__ . The value of __name__  attribute is set to '__main__'  when module run as main program. Otherwise the value of __name__  is set to contain the name of the module.

Consider the following code for better understanding.

Here we have defined a new module my_module . We can execute this module as main program by entering the following code

Expected Output:

here we are creating a new module and executing it as main program so the value of __name__ is set to '__main__' . As a result if condition satisfies and hello()  function gets called.
Now create a new file called using_module.py  and write the following code

Expected Output:

As you can see now if statement in my_module  fails to execute because the value of __name__  is set to 'my_module' .


Other Tutorials

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!


9
Leave a Reply

avatar
9 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
8 Comment authors
shakilaRohit GuptaAlexmayurVIiic Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
trackback

[…] *args and **kwargs What is if __name__ ==”__main__”?? […]

Shakti Das
Guest
Shakti Das

Nice Explanation bro i was searching from last 1 wk .but after reading your explanation my search stops hear.you are the python destiny.

Wu911
Guest
Wu911

Thanks so much, the best explanation i found on web !

Khanh N
Guest
Khanh N

The best explanation on this topic out of the ones I’ve been reading. Thank you!

VIiic
Guest
VIiic

thanks a lot. It’s very concise and clear 🙂

mayur
Guest
mayur

best and easy explanation of __name__

Alex
Guest
Alex

Thanks

Rohit Gupta
Guest
Rohit Gupta

thanks for the explanation

shakila
Guest
shakila

Thank you so much friend 🙂