How and why we use __name__=='__main__'
Python is such a popular language because it’s easy to use and it’s comprehensive. Previously, I covered what the keyword
yield was useful for and with some great feedback, I have decided to tackle another key feature:
Let’s get straight to it.
Now quite often you’ll see a file of the following format
# some functionality...
if __name__ == ‘__main__’:
At first, I struggled to understand why the file didn’t compile in one straight line but after learning about it, I began to appreciate it’s simplicity.
It comes down to a few things:
- You have some functions that people can use elsewhere
- You also want to run that file by itself at times
So it’s a bit of a quasi-library type of file. To appreciate it fully, first you should understand what values
__name__ can take.
What values can __name__ take? How does it work?
Let’s say that we have a file called
foo.py and the only thing in the file is the following:
Now if we run the following line on the command line:
We will get the following result:
But on the other hand, say we have another file
bar.py that contains:
And if you run
python bar.py you will get the following output:
See the difference?
If you run the file itself, then __name__ == ‘__main__’ but if you call __name__ from another file, then the name of the file is returned.
__name__ gets its value depending on how we execute the containing script. Only the file that you are running has a
__name__ set to
So what’s the purpose of __name__?
This feature allows you to both create a script which runs itself but also lends other scripts it’s functionality, so to minimise duplicating any coding.
So when you write a script containing a library of functions which can be useful in other places, this feature comes really handy.
Moreover, it allows you to create code that’s more efficient and dynamic for multiple users. You definitely want code that can easily scale as your team grows.
Python is such a popular language because features like this are well thought out and make life for the coder significantly easier. As more languages streamline their functionality to allow the coder to do less work, hopefully, coders have to carry less of the code and the language/compiler can do more.
Given that, features like I just explained can make life a hell of a lot easier, so I encourage you to use them!
Thanks again for reading! If you have any questions, please message =]
Keep up to date with my latest work here!