Purpose of 'if __name__ == "__main__":' [duplicate]

Solution 1:

Well, imagine that someone else wants to use the functions in your module in their own program. They import your module... and it starts doing its own thing!

With the if __name__ == "__main__", this doesn't happen. Your module only "does its thing" if it's run as the main module. Otherwise it behaves like a library. It encourages code reuse by making it easier.

(As Sheng mentions, you may want to import the module into another script yourself for testing purposes.)

Solution 2:

It is for unit test proposes.

If you are running this script directly, it will execute the if block. So you could do some unit test work here. But if you are importing this file as a module, you do not want this part to execute.

It is similar to the main function in Java. In every Java class, you could have a main function for unit test. But the class is imported/used as a module, the main function would not be executed.

Generally, if you're using this script directly, it will run the if block. Otherwise, someone would like to use this file as a library of function/class, and the test case name makes sure this code would not bother users.

Solution 3:

The if __name__ == '__main__' convention in Python is intended to allow you to write code that can be run directly, or imported.

If you import it, that if block is not executed. If you run python.exe myscript.py it is.

Solution 4:

This is the idiomatic way to tell whether the Python module was executed as a script, or imported from another module. You will only enter the if __name__ == "__main__" block if the file was executed as a script (aka, it is the main module).