0

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__":?

guagay_wk
  • 26,337
  • 54
  • 186
  • 295
  • When I googled the line, [this was the first result](https://docs.python.org/3/library/__main__.html). [This was the second](http://stackoverflow.com/questions/419163/what-does-if-name-main-do). Please try to research a question on your own before asking it here. – juanpa.arrivillaga Oct 12 '16 at 08:39
  • @juanpa.arrivillaga. I did google but I cannot understand what I read. The direct answers that just appeared on this question are easier to understand, thanks to SO community. – guagay_wk Oct 12 '16 at 08:41
  • *This was already answered on SO*. Please do not post duplicate questions if you know they are duplicates. – juanpa.arrivillaga Oct 12 '16 at 08:42

2 Answers2

3

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.

paul-g
  • 3,797
  • 2
  • 21
  • 36
  • Sounds like this line is necessary only for code that will be imported. Correct? – guagay_wk Oct 12 '16 at 08:39
  • 3
    @user91579631 yep, though in my personal experience, it's always 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 – paul-g Oct 12 '16 at 08:42
  • Thanks. Seems like it is good practice to always use `if __name__ == "__main__":` – guagay_wk Oct 12 '16 at 08:43
1

That is usefull when you are making a module or in general if you intend to import your scipt when running an other script. __name__ == "__main__" is true only when that script is the main script that is executed , so it avoids running subsequent code when it is ran at an import statement.

jadsq
  • 3,033
  • 3
  • 20
  • 32