What is if __name__ == “__main__” ??

(Sponsors) 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 '<strong>main</strong>'  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 '<strong>main</strong>' . As a result if condition satisfies and hello()  function gets called.
Now create a new file called 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 (Sponsors)

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!

17 thoughts on “What is if __name__ == “__main__” ??

  1. Pingback: Resources for Python | mEssy bYtes

  2. 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.

    1. Frank Kurka

      One use is:
      It prevents a program intended to run on its own from being used as a module
      (probably because it was not designed to be one and might not work properly as a module.)


Leave a Reply

Your email address will not be published. Required fields are marked *