What is if __name__ == '__main__' in Python ?
Last updated on December 24, 2022
The following is the most common pattern that trips people up..
1 2 | 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
import
statement. - 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
1 2 3 4 5 6 | def start_server():
# logic to start the server
print("Server started")
if __name__ == '__main__':
start_server()
|
Output:
1 2 | $ 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.
utils.py
1 2 | import my_server
print("utils.py executed")
|
Output:
1 2 | $ 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.
Load Comments