On Sun, 16 Nov 2008, Diez B. Roggisch wrote: > John O'Hagan wrote: > > On Sun, 16 Nov 2008, Diez B. Roggisch wrote: > >> > In other words, using the optparse object to hold as attributes > >> > everything needed by all the functions and methods in the module, and > >> > simply passing it holus bolus to all them and just pulling out what's > >> > actually needed inside the function, even adding new attributes or > >> > reassigning old ones along the way. > > > > [...] > > > >> > My question is: is this horribly inefficient or otherwise wrong? > >> > >> Partially, I do the same - passing around the opts-object so that I > >> don't have to e.g. pass verbosity-levels around explicit. > >> > >> *BUT* what I would *never* do is to assign to the options-object! If you > >> need state that changes and is something else that configuration, use a > >> class and instance-attributes together with self to communicate and > >> alter that state. The reason is simply that you don't do it much > >> differently now, but the options-object gets a god-like status it > >> shouldn't have. Without tracing all calls in the correct order, it is > >> impossible to say what state the object might have. > > > > I see your point but I want to be clear on the correct approach: to take > > my original example, is the following better: > > > > class State: > > pass > > state = State() > > ... > > def function_two(options, state): > > > > bar = options.option_two > > state.old_option_two = bar > > bar = bar * foo > > state.new_option_two = bar > > > > def function_three(options, state): > > blop = state.old_option_two > > ... > > ? [...] > > Make function_one and function_two methods of class "State" (you'd > obviously like to rename it something more useful then)
That hadn't occurred to me, as the real functions concerned (about a dozen) deal with different kinds of objects, it's just the (50+) options (and things derived from the options) that they need to share, to varying degrees. I guess I had thought of a class as something that deals with a particular type of "data". But I see that this is the way to go. > > Options are something that is given by the user. They should be considered > read-only. Any state that drives your logic should be explicit, and if > several functions rely on shared state, then a class is the usual answer. > Alternatively, you can of course pass explicit arguments. [...] Thanks for the helpful replies. Regards, John -- http://mail.python.org/mailman/listinfo/python-list