The benefits of __name__ == "__main__" in Python

Python

23 Jul 2020 | 4 minute read

Table of Contents

In your adventures with Python, you've probably seen the following quite a fair bit:

def main():
    pass

if __name__ == "__main__":
    main()

It's a standardized way of structuring your Python program and enables you to run your program. This article will dive deeper into the benefits of leaving the global space as soon as possible, and using the above pattern.

No side effects

When importing a package, would you prefer if the package executed code that you explicitly haven't asked it to execute? Probably not.

Unfortunately, that might happen if the package you're importing is doing things in the global space. One of the major benefits of using the main function is to leave the top level as soon as possible and to use functions instead.

For example, the author of the package might have decided that using if __name__ == "__main__" is superfluous, and the following is sufficient:

def main():
    pass

main()

Unfortunately (for us), the Python interpreter will start executing statements from the top of the file to the bottom of the file as the package is imported, and therefore the main function will be called even though we haven't asked for it. All we've done so far is to import the package.

Ouch. Probably not what we intended.

As the __name__ will equal "__main__" only when Python runs the file directly, it provides us with the flexibility of executing code in the program in different ways if it is imported or running as a standalone program.

Performance benefits

As local variable lookup is faster than global variable lookup in Python, having your code live inside of functions is an important performance optimization. Global variables that live at the top level of your module simply aren't as efficient as the local variables.

Depending on what your program is to do, performance optimisations such as this might be crucial.

Furthermore, in terms of developer performance, code that is well-structured and neatly placed in functions would be favourable as well. If you've ever inherited a piece of software where everything is placed in one big file without functions, you know exactly what I mean.

Stay in the loop

If you want to take part of new articles and tips and tricks to become a better developer, subscribe to my private email list:

Your thoughts? Please leave a reply 💬