What is if __name__ == "__main__" ??

Posted on Oct 31, 2019


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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# file my_module.py

foo = 100

def hello():
    print("i am from my_module.py")

if __name__ == "__main__":
    print("Executing as main program")
    print("Value of __name__ is: ", __name__)
    hello()

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

python my_module.py

Expected Output:

1
2
3
Executing as main program
Value of __name__ is: __main__
i am from my_module.py
# file my_module.py

foo = 100

def hello():
    print("i am from my_module.py")

if __name__ == "__main__":
    print("Executing as main program")
    print("Value of __name__ is: ", __name__)
    hello()

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, the if condition satisfies and the function hello() gets called.

Now create a new file called module.py and write the following code:

1
2
3
4
5
6
import my_module

print(my_module.foo)
my_module.hello()

print(my_module.__name__)

Expected Output:

1
2
3
100
i am from my_module.py
my_module

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


Other Tutorials (Sponsors)