1

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Mahmoud Hanafy
  • 7,958
  • 12
  • 47
  • 62

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
  • 854,327
  • 234
  • 1,573
  • 1,953
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.