Python - if__name__ == '__main__'
What is the __name__
variable?
__name__
is a built-in variable which evaluates to the name of the current module. Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement, as shown below.
If the source file is executed as the main program, the interpreter sets the __name__
variable to have a value “__main__
“. If this file is being imported from another module, __name__
14:09 2022/12/1 will be set to the module’s name.
How to use __name__
variable
Consider two separate files File1 and File2.
File1.py:
1 |
|
Now the interpreter is given the command to run File1.py.
$ python File1.py
Output :
File1__name__
=__main__
File1 is being run directly
And File2.py, which imports File1.py:
1 |
|
Then File2.py is run.
$ python File2.py
Output :
File1__name__
= File1
File1 is being imported
File2__name__
=__main__
File2 is being run directly
Then we could add the if __name__ == '__main__'
as the boilerplate code that protect us from invoking the imported scripts when we don’t intend to.
Rewrite the File1.py:
1 |
|
The re-run the File2.py
$ pyton File2.py
Output:
File1 is being imported
File2__name__
=__main__
File2 is being run directly
The function in File1.py has not been run but imported.
https://www.geeksforgeeks.org/__name__-a-special-variable-in-python/
https://stackoverflow.com/questions/419163/what-does-if-name-main-do
https://www.freecodecamp.org/news/whats-in-a-python-s-name-506262fe61e8/
http://blog.castman.net/%E6%95%99%E5%AD%B8/2018/01/27/python-name-main.html