In some python scripts, I see this format;
def main():
#run code
if __name__ == "__main__":
main()
In other python scripts, the line if __name__ == "__main__":
is not present but the code runs normally. Why have this extra redundant line when the code can run normally even without it? What is the advantage of using if __name__ == "__main__":
?
This line allows you to make some functionality run by default only when you run the script as the main script (e.g. python my_script.py
).
This is useful when the script may be used either as a main program or to be imported in another python module, or python shell. In the latter case you would almost certainly not want main (or other module functionality) to run on import, which is what happens by default when the interpreter loads a script.
If you'll never import this script in other code, or in a python shell then you don't need this line. However, it's good to design your code to be modular & import friendly; even what may appear as throw away scripts (e.g. plotting some numbers, parsing some logs etc.) may be useful in a larger context. Particularly in an interactive shell session, e.g. using ipython
. And the cost is small: encapsulate statements in functions and add ifmain
.