What does if __name__ == “main” do in Python?
An introduction to the __name__ variable
You probably seen the __name__
variable if you’ve gone through some python
open source code. For instance below:
|
|
Whenever the python interpreter reads a source file, it does two things:
- sets a few special/global variables like
__name__
, then; - executes all of the code found in the file.
Why is the __name__ variable used?
The __name__
is a special python variable. It gets it’s value depending on how
we execute the containing module.
Sometimes you write a module with functions that might be useful in other module as well. In python, you can import that module into another module.
Thanks to this special variable, you can decide whether you want to run the the whole module. Or you want to import the functions defined in the module.
To grasp the context more vividly let see some use case examples.
Use Case
Let’s assume that we have module which has a simple function called get_max()
to
get the maximum integer in a given array:
|
|
if we run this module we get the below result:
$ python module_one.py
Hello Module 1
max int: 9
Issue
So now assume that we need this get_max()
function from other module that we
write:
|
|
If we now run the module_two.py
we get the output:
$ python module_two.py
Hello Module 1
max int: 9
Hello Module 2
max int: 17
According to our program, the output should be “17” because the
only get_max()
function is called. But the whole module is imported.
Solution
To overcome this we use if __name__ == “__main__”
. The extra line of codes
written after function get_max()
in module_one.py
is kept inside of it so it
won’t be executed while the function is imported in module_two.py
.
Now update our module_one.py
like below:
|
|
Now run the module_two.py
:
$ python module_two.py
Hello Module 2
max int: 17
You see that after using if __name__ == “__main__”
the unrelated codes will
not be used by module_two.py
.
Conclusion
After all that we understand that what does if __name__ == “__main__”
do in
python; it prevents certain code to run if any other file imports it.
All done!
Changelog
- 2021-05-02 : Fixed typo and improve subtitles