I know the --verbose or -v from several tools and I’d like to implement this into some of my own scripts and tools.
I thought of placing:
if verbose:
print ...
through my source code, so that if a user passes the -v option, the variable verbose will be set to True and the text will be printed.
Is this the right approach or is there a more common way?
Addition: I am not asking for a way to implement the parsing of arguments. That I know how it is done. I am only interested specially in the verbose option.
My suggestion is to use a function. But rather than putting the
ifin the function, which you might be tempted to do, do it like this:(Yes, you can define a function in an
ifstatement, and it’ll only get defined if the condition is true!)If you’re using Python 3, where
printis already a function (or if you’re willing to useprintas a function in 2.x usingfrom __future__ import print_function) it’s even simpler:This way, the function is defined as a do-nothing if verbose mode is off (using a lambda), instead of constantly testing the
verboseflag.If the user could change the verbosity mode during the run of your program, this would be the wrong approach (you’d need the
ifin the function), but since you’re setting it with a command-line flag, you only need to make the decision once.You then use e.g.
verboseprint("look at all my verbosity!", object(), 3)whenever you want to print a "verbose" message.If you are willing and able to use the Python
-Oflag to turn verbosity on and off when launching the "production" version of the script (or set thePYTHONOPTIMIZEenvironment variable) then the better way is to test the__debug__flag everywhere you want to print a verbose output:When run without optimization, these statements are executed (and the
ifis stripped out, leaving only the body of the statement). When run with optimization, Python actually strips those statements out entirely. They have no performance impact whatsoever! See my blog post on__debug__and-Ofor a more in-depth discussion.