Usage for if "__name__" == "__main__":
If the module we import, in addition to defined functions, still has executable code. Then python interpreter would execute this code which is unexpected. Therefore, if we write executable code in modules, better put this code in if "__name__" == "__main__":
so that the code under “if” condition won’t be executed unless to execute its module directly. Since only the name of the module to be executed directly is "__main__"
.
model3.py
1 | def foo(): |
test.py
1 | # When import module3, the code under if condition in module3 won't be executed since its name is module3 rather than "__main__" |