4 ms·
"if name == “__main__” isn't magic, it serves a purpose. Sometimes name == “__main__” and sometimes it doesn't, and I want to specify different behavior in dif
by jpindar 6y ago
"if name == “__main__” isn't magic, it serves a purpose. Sometimes name == “__main__” and sometimes it doesn't, and I want to specify different behavior in different cases.
Here, name is the name of the module. When the module is run by itself, this is the same as __main__, in which case I want the things specified by the if to run right away. This could be calling a main function, but a lot of times it's just is some tests or examples.
When the module is imported into another file, it's name is not the same as __main__. In this case I usually only want things in it to do stuff when they are called by the other file.
This doesn't have anything to do with a function literally called "main" though.
if __name__ == "__main__":
main()
Is a common idiom, but there's no connection between the two uses of the word main.