Global variable visibility
Aahz
aahz at pythoncraft.com
Fri Nov 1 01:35:34 EST 2002
In article <mailman.1036107510.2298.python-list at python.org>,
David LeBlanc <whisper at oz.net> wrote:
>
>I have main.py which imports database.py, commands.py
>
>Global variable Db is initialized in main.py after importing
>database.py but before importing commands.py. Commands.py uses Db,
>but can't "see" it in main.py. Is there a way to make it so that
>commands.py picks up Db, or do I have to do as I did and create a Db =
>none at the commands.py global level and then pass in an initializer
>for the global? This variable is used so pervasivly that it doesn't
>make sense to pass it as an argument to every function.
>
>Is there a fully qualified name for a global in main that could be used
>from an import?
Yes, but Don't Do That. Here are two options:
import commands
commands.Db = Db
or
import commands
commands.set_db(Db)
# in commands.py
def set_db(newDb):
global Db
Db = newDb
Both of these only work if Db is either static or mutable; if you rebind
__main__.Db, your program will have R-E-A-L problems.
--
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
Project Vote Smart: http://www.vote-smart.org/
More information about the Python-list
mailing list