What is if __name__ == “__main__” ??

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

Leave a Reply

1 Comment on "What is if __name__ == “__main__” ??"

Notify of

Sort by:   newest | oldest | most voted

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