If you have been programming in Python for a bit it is probable you came across the code if __name__ == “__main__” and that you, like me and many others before, had no clue of what it means. Below a short explanation of how I understood it. Hope it helps!
The main function is essentially where any Python program starts. The Python interpreter (= program, which reads and executes code) sequentially reads the source file (= module) and executes the code.
Remember, the main function can only be processed if the interpreter reads it as a Python program! Otherwise, it is ignored.
This is why the following code will not return anything:
def main(): print(2+2)
It is seen as a module and hence skipped! Essentially, the function is just defined, and not yet called.
In Python 3 (or later) an easy solution would be to easily call the main function at the end of the code for the function:
def main(): print(2+2) main()
This calls the main function and executes the code.
Another solution is to call the code in the main function we want to run if the “special” variable (see below) __name__ is equal to “__main__”:
def main(): print(2+2)if __name__ == “__main__”: main()
Why does this work? Before executing code, the Python interpreter reads the source file and defines a few “special” variables. The variable __name__ is one of these and evaluates the name of the current module.
If the Python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value “__main__”. The if statement allows checking whether a function is run from the current script or if it has been imported from another one.
If it is imported from another module, __name__, will be set to that script’s name!