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.
You should expect that a user running your code as an executable has different goals than a user importing your code as a package. The if __name__ == ‘__main__'
statement provides control flow based on the environment in which your code is being executed.
__name__
is a special variable in the module’s global namespace- It has a
repr()
method that is set by Python - The value of
repr(__name__)
depends on the execution context - From the command line,
repr(__name__)
evaluates to ‘__main__’ — therefore any code in the if block will run - Imported as a package,
repr(__name__)
evaluates to the name of the import — therefore code in the if block will not run
Why is this helpful? Well, someone running your code from the command line will have the intention of executing functions right away. This may not be true of someone importing your package as utility code into a Jupyter Notebook.
In if __name__ == ‘__main__'
you should create a function called main()
that contains the code you want to run. Across programming languages, the main function provides an entry point for execution. In Python, we name this function main()
only by convention — unlike lower level languages, Python does not ascribe any special significance to the main function. By using the standard terminology however, we let other programmers know that this function represents the starting point of the code that accomplishes the primary task of the script.
Rather than including blocks of task-accomplishing code within main()
, the main function should call other functions stored within the module. Effective modularization allows the user to reuse aspects of the code as they wish.
The extent to which you modularize is up to you — more functions means more flexibility and easier reuse, but may make your package more difficult for a human to read and interpret as they traverse logical breaks between functions.