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!

Leave a Reply

4 Comments on "What is if __name__ == “__main__” ??"

Notify of
avatar

Sort by:   newest | oldest | most voted
Khanh N
Guest
Khanh N
16 days 19 hours ago

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

Wu911
Guest
Wu911
17 days 6 minutes ago

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

Shakti Das
Guest
Shakti Das
1 month 12 days ago

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

trackback

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

wpDiscuz