What does “__name__” mean in Python?

Original article was published on Artificial Intelligence on Medium

What does “__name__” mean in Python?

How and why we use __name__='__main__'

Photo by Nick Fewings on Unsplash

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: __name__ .

Let’s get straight to it.

Now quite often you’ll see a file of the following format

import librarydef main():
# some functionality...
return library.function()
if __name__ == ‘__main__’:
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:

  1. You have some functions that people can use elsewhere
  2. 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:

print(__name__)

Now if we run the following line on the command line:

python foo.py

We will get the following result:

__main__

But on the other hand, say we have another file bar.py that contains:

import foo
print(foo.__name__)

And if you run python bar.py you will get the following output:

foo

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.

So __name__ gets its value depending on how we execute the containing script. Only the file that you are running has a __name__ set to ‘__main__’.

Photo by Keith Luke on Unsplash

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.