[Tutor] Newbie: "Global" vars across modules
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Wed Dec 3 17:31:21 EST 2003
On Wed, 3 Dec 2003, Alan Trautman wrote:
> My favorite method, from a discussion on this list is to create a module
> and import it into all modules that need access. I name it
> myappname_globals.py and it contains things like database name, debug
> level, and other constants that might need changing. A config file is
> the other option I use if there is a lot to configure. If debug level is
> the only reason a command line argument is safest.
>
> This is the one of the very few cases where I like FROM
> myappname_globals.py IMPORT *. this means that the variable names are
> the same in every case.
Hi Alan,
Be careful with 'from foo import *'. The variable names are the same
here, but the values will not necessarily be the same. For example, let's
say we have three files: globals.py, a.py, and b.py
###
"""globals.py"""
X = 42
###
###
"""a.py"""
from globals import *
def setX():
global X
X = 17
###
###
"""b.py"""
import globals
def setX():
globals.X = 17
###
The second form, in 'a.py', is error prone: it does set X to by 17
throughout the 'a' module, but that value is limited to the module. That
is, the following program:
###
from globals import *
import a
a.setX()
print X
###
should still print 42.
If we treat our global variables as constants, this isn't a problem ---
it's when we start assigning to globals that this Bad Thing can happen.
'b.py' is more in spirit with the way that global variables work, and
should avoid any surprises.
###
import globals
import b
b.setX()
print globals.X
###
should do what you expect.
This being said: avoid global variables if you can! *grin*
But are you sure you're not reinventing the wheel? The 'logging' module:
http://python.org/doc/current/lib/module-logging.html
already provides a way of distinguishing debugging messages based on a set
of log levels (DEBUG, INFO, WARNING, ERROR and CRITICAL). With the
'logging' module, your program snippets:
> --begin gvars.py--
> # Debug Level (0=NONE, 1=Normal, 2=Extended, 3=Verbose)
> debug_level = 2
>
>
> --myFunctions.py--
> def ftest():
> if (debug_level = 3):
> print "VERBOSE DB: This is a verbose statement"
> return 1
can be translated as:
###
--begin gvars.py--
import logging
logging.getLogger().setLevel(logging.INFO)
--myFunctions.py--
import logging
def ftest():
logging.getLogger().debug("This is a verbose statement")
return 1
###
and 'logging' is pretty full featured already, so unless you're just
trying to learn how to use global variables, I'd recommend using the
'logging' module --- it's quite handy.
Good luck to you!
More information about the Tutor
mailing list