Wandering Thoughts archives


The options problem in Python

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:

  • global variables for each option or setting. This involves a profusion of global variables, which doesn't make me happy.

  • a single global 'options' object, which holds all of the options and settings (probably in expanded form).

  • passing individual variables for each option down the call chain to routines that need them. The problem with this is that you wind up with large argument lists that are passed to a lot of high level functions purely so that the functions can pass them along to low level routes as needed.

  • passing a single 'options' object down the call chain to routines that need any option. This at least adds fewer parameters to calls, but you pretty soon wind up in a situation where your options object is effectively a global variable that's being passed as part of the function arguments.

(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.)

python/OptionsProblem written at 03:03:27; Add Comment

Page tools: See As Normal.
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.