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?
We can use an if __name__ == "__main__" block to allow or prevent parts of code from being run when the modules are imported. When the Python interpreter reads a file, the __name__ variable is set as __main__ if the module being run, or as the module's name if it is imported.
The main function in Python acts as the point of execution for any program. Defining the main function in Python programming is a necessity to start the execution of the program as it gets executed only when the program is run directly and not executed when imported as a module.
if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.
Understanding the __main__ Function in Python Using if __name__ == '__main__' provides the flexibility to write code that can be executed from the command line or imported as a package into an interactive environment. This conditional statement controls how the program will execute given the context.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With