What is if __name__ == ‘__main__’ in Python ?

The following is the most common pattern that trips people up.

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:

  1. Using the import statement.
  2. As the main module by passing module name to the Python interpreter (i.e python module_name.py).

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

This pattern helps us to execute some logic only when the module is run as the main module.

my_server.py

Output:

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.

utils.py

Output:

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.

Leave a Comment