What is if __name__ == '__main__' in Python ?
Last updated on July 27, 2020
The following is the most common pattern that trips people up.
if __name__ == '__main__': # some logic here
Every Python module defines a variable called
__name__. It can either contain module name or
__main__ depending upon how a module is executed.
We can execute a Python file (or module) in two ways:
- Using the
- As the main module by passing module name to the Python interpreter (i.e
If a module is imported inside another module, then the
__name__ variable in the imported module refers to the module name. On the other hand, if a module is executed as the main module (i.e. module which starts the program), then the
__name__ variable contains
This pattern helps us to execute some logic only when the module is run as the main module.
1 2 3 4 5 6
def start_server(): # logic to start the server print("Server started") if __name__ == '__main__': start_server()
$ python my_server.py Server started
In this example, we are able to call
start_server() function because we are running
my_server.py as the main module. Now let's see what would happen if we import our main module inside another module.
import my_server print("utils.py executed")
$ python utils.py utils.py executed
As you can see, this time the
start_server() function from
my_server.py module is not called because we are not executing
my_server.py as the main module.