DEV Community

Cover image for What is __name__ == '__main__' in python 🤯
Vamsi Krishna
Vamsi Krishna

Posted on

What is __name__ == '__main__' in python 🤯

if __name__ == '__main__':
    pass
Enter fullscreen mode Exit fullscreen mode

Many people on YouTube and also in the in-built modules in python there is this statement which confuses the most of the beginners who are trying to learn python. In this post I will try to clarify about what is __name__ and why it is used in python?

What is __name__?

Before running any python script or file, python itself sets some special variables and this __name__ is one of the variables. The beauty of this variable is that it sets the value of variable based on how we run the file. For example, if we run the file directly then it gets __main__ as the value but if we run this file by importing it into other file and running that file it gets a the file name as the value and that other file will get __main__ as the value.

Let us see in deep :

Let us create two files named first.py and second.py
Add following code to first.py file 👇

def main():
    print('first.py file __name__ :', __name__)

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Above code is very simple that if __name__ is equal to __main__ only then we will run our main() method which actually means is that when the file is ran directly then the __name__ variable will be equal to __main__ only then our main() method will be executed.

try to run the first.py file alone, we will get the following output

first.py file __name__ : __main__
Enter fullscreen mode Exit fullscreen mode

Now Add the following code to second.py file 👇

import first

print('second.py file __name__ :', __name__)
Enter fullscreen mode Exit fullscreen mode

if we run the second.py file we will get the following output

second.py file __name__ : __main__
Enter fullscreen mode Exit fullscreen mode

If we look carefully we are importing our first.py module into second.py but we are not getting any output from first main() method. this is because the first file is not ran directly so the __name__ will not be equal to __main__ it is actually equal to first.

then how can we get the first.py __name__ variable?

to get that just change second.py code as below..

import first

first.main()
print('second.py file __name__ :', __name__)
Enter fullscreen mode Exit fullscreen mode

then we will get the following output 👇

first python file __name__ : first
second.py file __name__ : __main__
Enter fullscreen mode Exit fullscreen mode

I hope you have got some basic idea about __name__ variable..
Thank You for reading 💗

Top comments (0)