What Does if __name__ == “__main__” Do in Python?

You’ve likely encountered Python’s if __name__ == "__main__" idiom when reading other people’s code. No wonder—it’s widespread! You might have even used if __name__ == "__main__" in your own scripts. But did you use it correctly?

Maybe you’ve programmed in a C-family language like Java before, and you wonder whether this construct is a clumsy accessory to using a main() function as an entry point.

Syntactically, Python’s if __name__ == "__main__" idiom is just a normal conditional block:

 1if __name__ == "__main__":
 2    ...

The indented block starting in line 2 contains all the code that Python will execute when

 

 

 

To finish reading, please visit source site