Google has a Python tutorial, and they describe boilerplate code as \"unfortunate\" and provide this example:
#!/usr/bin/python
# import modules used here -- sy
The reason that the if __name__ == "__main__":
block is called boilerplate in this case is that it replicates a functionality that is automatic in many other languages. In Java or C++, among many others, when you run your code it will look for a main()
method and run it, and even complain if it's not there. Python runs whatever code is in your file, so you need to tell it to run the main()
method; a simple alternative would be to make running the main()
method the default functionality.
So, if __name__ == "__main__":
is a common pattern that could be shorter. There's no reason you couldn't do something different, like:
if __name__ == "__main__":
print "Hello, Stack Overflow!"
for i in range(3):
print i
exit(0)
This will work just fine; although my example is a little silly, you can see that you can put whatever you like there. The Python designers chose this behavior over automatically running the main()
method (which may well not exist), presumably because Python is a "scripting" language; so you can write some commands directly into a file, run it, and your commands execute. I personally prefer it the Python way because it makes starting up in Python easier for beginners, and it's always nice to have a language where Hello World is one line.