What's the point of a main function and/or __name__ == "__main__" check in Python?

Question:

I occasionally notice something like the following in Python scripts:

if __name__ == "__main__":
    # do stuff like call main()

What’s the point of this?

Asked By: Richard Simões

||

Answers:

The sole purpose of this, assuming it is in main.py, is so other files can import main to include classes and functions that are in your “main” program, but without running the source code.

Without this condition, code that is in the global scope will be executed when it is imported by other scripts.

Answered By: Fragsworth

This allows a python script to be imported or run standalone is a sane way.

If you run a python file directly, the __name__ variable will contain __main__. If you import the script that will not be the case. Normally, if you import the script you want to call functions or reference classes from the file.

If you did not have this check, any code that was not in a class or function would run when you import.

Answered By: Jesse Vogt

Having all substantial Python code live inside a function (i.e., not at module top level) is a crucial performance optimization as well as an important factor in good organization of code (the Python compiler can optimize access to local variables in a function much better than it can optimize “local” variables which are actually a module’s globals, since the semantics of the latter are more demanding).

Making the call to the function conditional on the current module being run as the “main script” (rather than imported from another module) makes for potential reusability of nuggets of functionality contained in the module (since other modules may import it and just call the appropriate functions or classes), and even more importantly it supports solid unit testing (where all sort of mock-ups and fakes for external subsystems may generally need to be set up before the module’s functionality is exercised and tested).

Answered By: Alex Martelli

It’s a great place to put module tests. This will only run when a module is run directly from the shell but it will not run if imported.

Answered By: flexterra
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.