Tuesday, August 27, 2019

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

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

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...