Accessing variables in __main__ from modules....

Roland Schlenker rol9999 at attglobal.net
Thu Mar 29 15:45:16 EST 2001


nanotech at europa.com wrote:
> 
> All:
> 
> When writing programs, I like to add print statements that are only
> displayed when the user provides a command line switch such as '--
> debug'.
> 
>   Ex:  %myprog spam.txt ham
>        Found the word 'ham' in 'spam.txt' 45 times
> 
>        %myprog --debug spam.txt ham
>        -I-: Reading 'spam.txt'....has 213 lines....
>        Found the word 'ham' in 'spam.txt' 45 times
> 
> Now, say most of the work is done in a module 'spam.py'. If I wrote
> code in this module like:
> 
>   lines=open(filename).readlines()
>   if (DEBUG):
>     print "-I-: Reading '%s'....has %s lines...."%(filename,len
> (lines))
> 
> DEBUG would be searched for at the module scope. But I want it to
> look for DEBUG back in __main__, like:
> 
>   if (sys.modules["__main__"].DEBUG):
>     print "-I-: Reading '%s'....has %s lines...."%len(filename,lines)
> 
> Is this the "best" way to access variable in the "__main__" scope?
> How else might I solve this (in the python way)??
> 
> Quentin Crain
> 
> Note: I might load many modules all wanting to know if DEBUG is
> turned on. I do not want to pass DEBUG to functions or classes and I
> do not want to set a module variable DEBUG to the same value
> (module1.DEBUG=DEBUG, module2.DEBUG=DEBUG, etc. in __main__). Unless
> these are "better" solutions! :)

How about a module named globals, which contains one line:

DEBUG = 0

Have all your modules import globals.

In __main__ when you want to perform debugging, set DEBUG = 1 in
globals.

Then write your conditional as:

if (globals.DEBUG):
  print "-I-: Reading '%s'....has %s lines...."%(filename,len(lines))

Roland Schlenker




More information about the Python-list mailing list