"Boilerplate" code in Python?

Bhaxy picture Bhaxy · Oct 26, 2011 · Viewed 46.3k times · Source

Google has a Python tutorial, and they describe boilerplate code as "unfortunate" and provide this example:

#!/usr/bin/python

# import modules used here -- sys is a very standard one
import sys

# Gather our code in a main() function
def main():
  print 'Hello there', sys.argv[1]
  # Command line args are in sys.argv[1], sys.argv[2] ..
  # sys.argv[0] is the script name itself and can be ignored

# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
  main()

Now, I've heard boilerplate code being described as "seemingly repetitive code that shows up again and again in order to get some result that seems like it ought to be much simpler" (example).

Anyways, in Python, the part considered "boilerplate" code of the example above was:

if __name__ == '__main__':
  main()

Now, my questions are as follows:

1) Does boilerplate code in Python (like the example provided) take on the same definition as the definition I provided? If so, why?

2) Is this code even necessary? It seems to me like the code runs whether or not there's a main method. What makes using this code better? Is it even better?

3) Why do we use that code and what service does it provide?

4) Does this occur throughout Python? Are there other examples of "boilerplate code"?

Oh, and just an off topic question: do you need to import sys to use command line arguments in Python? How does it handle such arguments if its not there?

Answer

Winston Ewert picture Winston Ewert · Oct 26, 2011
  1. It is repetitive in the sense that it's repeated for each script that you might execute from the command line.
  2. If you put your main code in a function like this, you can import the module without executing it. This is sometimes useful. It also keeps things organized a bit more.
  3. Same as #2 as far as I can tell
  4. Python is generally pretty good at avoiding boilerplate. It's flexible enough that in most situations you can write code to produce the boilerplate rather then writing boilerplate code.

Off topic question:

If you don't write code to check the arguments, they are ignored.