1

Possible Duplicate:
What does <if name==“main”:> do?

Often, I see the following code in python programs

if __name__ == '__main__':
main()

I'm following the Python Class on Google code, and it says that it's standard boilerplate code.

Do I really need to write such code in all my scripts?

What functionality would this add to my programs?

Community
  • 1
  • 1
Mahmoud Hanafy
  • 7,552
  • 10
  • 43
  • 61

2 Answers2

2

No, you don't have to, but it's invaluable for things like unit testing.

You can create a main in every python file so that, if you run it directly, __name__ will be set to "__main__" and it will run a barrage of tests on the code in question.

If you just import it normally from another program, that doesn't happen, because __name__ is set to a different value.

paxdiablo
  • 814,905
  • 225
  • 1,535
  • 1,899
0

It is helpful, when you're importing the files. You can either run the python file as a standalone program, or import some components of it into another programs.

Tadeusz A. Kadłubowski
  • 7,642
  • 1
  • 28
  • 36