Python: if __name__ == “__main__”

There are plenty of articles on the internet that attempt to explain what  if __name__ == "__main__" is and what it does, but (in my humble opinion), the examples are too complex more often than not. With that in mind, this post is aimed at being the most simplest explanation on the planet! :)

What does it do?

This statement is used when you want your code to be used as both a standalone script, as well as a module that can be imported and used by other scripts.

For example, if it is run as a standalone script, you may want to provide a menu to ensure users input all of the necessary information. On the other hand, if it is being imported as a module, perhaps you’d like to avoid the menu all together and instead only use the functions contained the script (e.g func1 in the example below).

To achieve the above outcome, you would use the following code:

How does it work?

Although __name__  is sometimes referred to as a “magic method”, it really isn’t all that exciting. As we’ll see in a moment, it does one of two things:

  1. If it is run against an imported module, it will return the name of the file which contains the module’s code.
  2. If it is run against a script that is not being imported, it will return __main__.

Let’s now look at two files, and

Running the file results in the following output:

Running the file results int he following output:

Knowledge Base

See the Coding section of my Knowledge Base for more information.
As always, if you have any questions or have a topic that you would like me to discuss, please feel free to post a comment at the bottom of this blog entry, e-mail at, or drop me a message on Twitter (@OzNetNerd).

Note: This website is my personal blog. The opinions expressed in this blog are my own and not those of my employer.