Application-global "switches"?

Ethan Furman ethan at stoneleaf.us
Fri Sep 4 22:24:39 CEST 2009


kj wrote:
> 
> 
> I'm looking for the "best-practice" way to define application-global
> read-only switches, settable from the command line.  The best
> example I can think of of such global switch is the built-in variable
> __debug__.  This variable is visible everywhere in a program, and
> broadly affects its operation.
> 
> The situation that prompts this question is the task of implementing
> a certain application that is supposed to run for several days
> (typically 2-3 weeks).  It is important to be able to re-start this
> application where it left off in case that, for some reason (e.g.
> internet connection failure), it terminates prematurely.  When this
> application is restarted its behavior is somewhat different from
> when it is started from scratch.  (For example, when it is re-started,
> it does not clear certain directories.)
> 
> Hence, I'd like to be able to have a variable, e.g. CONTINUATION_MODE,
> visible everywhere in the code, that tells the application to behave
> in "continuation mode", so that I can write stuff like
> 
>     if not CONTINUATION_MODE:
>         clean_the_slate()
> 
> The only solution I can come up with is to define a "dummy module",
> say _config.py, which contains only upper-case variables representing
> these global switches, and is imported by all the other modules in
> the application with the line "from _config import *".  During the
> early stages of the run, the script inspects the command-line flags,
> and if it finds a --continuing flag, it sets the variable
> _config.CONTINUATION_MODE to True.  (The last point implies that
> these variables are not strictly speaking read-only, since they
> most be set at the beginning of the run.  But after this initial
> setting, they should remain read-only.)
> 
> I'm sure this would work OK, but I wonder if there is a more Pythonic
> way to do this sort of thing.  Is there a best practice for setting
> such application-global switches?
> 
> TIA!
> 
> kynn

I've seen a couple cool recipes implementing WORM* attributes if you 
wanted to ensure that your settings were not re-set.

Steven D'Aprano wrote one with a class name of ConstantNamespace, you 
can search on that if you're interested.  I'd include the code, but I 
have no idea if that's good netiquette or not.

~Ethan~

*Write Once Read Many, for those unfamiliar with the term



More information about the Python-list mailing list