The options problem in Python
September 17, 2012
Suppose that you have a Python program that takes command line arguments, including switches (a 'verbose' switch is common, for example). These options change the program's behavior and logic in relatively low-level places, possibly pervasively (again a 'verbose' switch is a good example, as is a 'dryrun' switch).
So, how do you pass information about these command-line arguments down to low-level code? I can think of at least four, most of which I've used in my code from time time, and I have no idea which is considered the best and most Pythonic. The four that come to mind are:
(Let's assume for the moment that you can't restructure your program in any natural way to localize knowledge about a particular option in a single small place; you really do have pervasive options.)
I don't really like any of these, although in some situations some of them are less annoying than others. Since I continue to not like global variables, right now I usually do some variant of the third or the fourth without any real enthusiasm for it.
I feel like there should be a better way, if only I was clever enough to see it.
(All of this is on my mind right now because I'm confronting one of my old programs with what is now bad argument handling and thinking about overhauling all of it.)
* * *
Atom feeds are available; see the bottom of most pages.