What does __name__=="__main__" mean in Python ?


In this tutorial, you’ll learn what does name==’main’ mean in Python.

All python beginners, once in a while must have stumbled upon the below piece of code.

# 
__name__=='__main__'

What does it actually mean and what is the use of the above piece of code. We’ll see what the above code does and its relevance with the help of an example.

What does __name__==’__main__’ mean in Python ?

Lets create a simple python program hello.py with a function called foo.

#!/usr/bin/python
# hello.py

def foo():
    print 'foo is called'

foo()

If you try running the above program, you should have the following output on the console.

# output
foo is called

Now, suppose we need to import this hello.py file into another python program in order to access the foo function.
Let’s create another python program called world.py. In world.py we’ll import our hello.py and try to call foo. Here is how_world.py_ would look like:

#!/usr/bin/python
# world.py

import hello

def bar():
    hello.foo()

bar()

Now, if you execute world.py, you should have the following output on the terminal console;

foo is called
foo is called

We’ll as you saw the message gets printed twice. The simple solution would be to remove the foo function call from_hello.py_. But in that case it won’t print the message when we execute hello.py. Well, this is where

# Our Hero ;)
__name__=='__main__'

comes into the picture. When a python program starts to execute, it sets a few special variable, __name__ is one of them. It contains the value __main__ if it’s the main program being executed. But it won’t have the value as __main__ being set, if it’s being imported and executed, since it’s not the main program when imported.
Let’s modify hello.py to include the checking for name .

#!/usr/bin/python
# hello.py

def foo():
    print 'foo is called'

if __name__ == '__main__':
    foo()

Now, if you try running the world.py program it won’t print the message twice. The only message that is printed is of the hello.foo function call.

Wrapping It Up

In this short tutorial, you learnt what does name==’main’ mean in Python. Hope the python examples were clear.

Do let us know your thoughts in the comments below.