Python – What’s the point of a main function and/or __name__ == “__main__” check in Python?


Possible Duplicate:
What does <if __name__==”__main__”:> do?

I occasionally notice something like the following in Python scripts:

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

What's the point of this?

Best Solution

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).