Global variables in different moduls
Philip Swartzleonard
starx at pacbell.net
Sun May 5 14:03:44 EDT 2002
jb || Sun 05 May 2002 10:44:52a:
> I have a module globals.py, where I store som global variables, for
> example the variable <x>. So the first line of globals.py is
>
> x = None
>
> The module globals.h is imported in the module main.py and other.py
> (and in several other modules).
>
> Now when the main program starts in main.py, the first statement is
>
> x=3
>
> but later in other.py <x> still has the value None. Am I making a
> mistake somewhere or is this normal?
>
>
Just a little bit of a mistake =). The thing is, import only makes the
name following the keyword immediatly available where you put it. So the
name 'x' that you're using is still a local variable, and that's where
your problems are coming from. But you generally treat modules like
objects, so you can say:
# in one file:
import globals
globals.x = 3
# ...
# later in another file:
import globals
print globals.x
If you really want that 'x' variable 'right here, so i can use it
without a prefix', what you want is either:
from globals import x
or
from globals import * # Generally Not Reccomended
... i would generally not recommend doing either with such a small
variable name anyway (not that i reccomend using small variable names in
most cases =).
If you have used C before, you are probably used to the #include
statment that basically copies all of the text in one file into another.
There's nothing exactly like that in python, 'from x import *' is the
closest thing. In python, we can do better =).
Oh, one more tiny thing. Don't name your module globals. There's a
built-in function of the same name, returns a dictionary of the current
global variables. Not much use until you need to spawn an interperter
window or do some kind of (restricted) execution, but then you'll
suddenly have 'module is not a function' errors that don't really make
any sense (been there, done that). Don't use glob, it's a standard
module... maybe 'glo', or 'project'. 'config' is popular, but I would
only use it if the file contained a bunch of initilizations and contants
that the user could tweak to change the behaviour of the program.
Anyway, good luck =)
--
Philip Sw "Starweaver" [rasx] :: www.rubydragon.com
More information about the Python-list
mailing list