What does if __name__ == “__main__”: do?
If you have started working with python, then in python files you must have seen the following code as the last lines
if __name__ == "__main__":
main()
Being a NodeJS/Angular developer, I was confused about this line. So here is the explanation
- import a action actually runs all that can be ran in a.py, meaning each line in a.py
- Because of point 1, you may not want everything to be run in a.py when importing it
- To solve the problem in point 2, python allows you to put a condition check
- __name__ is an implicit variable in all .py modules:
- when a.py is imported, the value of __name__ of a.py module is set to its file name "a"
- when a.py is run directly using "python a.py", the value of __name__ is set to a string __main__
5. Based on the mechanism how python sets the variable __name__ for each module, do you know how to achieve point 3? The answer is fairly easy, right? Put a if condition: if __name__ == "__main__": // do A
- then python a.py will run the part // do A
- and import a will skip the part // do A
6. You can even put if __name__ == "a" depending on your functional need.
Reference
https://stackoverflow.com/questions/419163/what-does-if-name-main-do#:~:text=In%20short%2C%20use%20this%20'%20if,when%20the%20module%20is%20imported.&text=Put%20simply%2C%20__name__,run%20as%20an%20imported%20module.