[Tutor] Use of a global variable in many scripts
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Sat, 23 Mar 2002 02:15:39 -0800 (PST)
On Fri, 22 Mar 2002, Aldo Duran wrote:
> Hello everyone
>
> I am new to python and I have some questions, here is my first.
>
> I have a set of scripts, and I would like to use a variable being set in
> the main program and use in all the others scripts. I have a file1.py
> which defines global variabel var1 and then I import file2.py, I tryed
> to use the variable from file2.py, but I get the exception
>
> Traceback (most recent call last):
> File "/tivoli/homes/4/aduran/bin/py/file1.py", line 7, in ?
> file2.useVar1()
> File "/tivoli/homes/4/aduran/bin/py/file2.py", line 6, in useVar1
> print var1
> NameError: global name 'var1' is not defined
>
> How can I use the same global variables in all my scripts?
Hi Aldo,
If we imported by doing something like:
###
import file1
###
that does give us access to the 'var1' variable, but we still need to name
the package that we're reading from:
###
print file1.var1
###
If we'd like to copy over a variable from the other module, we can do
something like
###
var1 = file1.var1
###
And to save some effort, there's a specialized way of pulling variables
'from' modules:
###
from file1 import var1
###
> I know that using global variables is not a very good practice but
> sometimes it is easy, convenient, quick and simple.
Agreed... but we still recommend not doing it. *grin* At least, not in a
widespread way. It may be possible to do what you're trying to do in a
more direct fashion, without using global variables to communicate between
functions or modules.
> file1.py
> -------------------------------------------------
> #!/usr/bin/env python2.2
>
> global var1
> var1 = 1
> import file2
>
> file2.useVar1()
>
> file2.py
> -------------------------------------------------
> #!/usr/bin/env python2.2
>
> global var1
>
> def useVar1():
> print "var1 value == " ,var1
To get the variable 'var1' so that file2 can access it, you can do
something like this at the beginning of file2:
###
from file1 import var1
###
But in this particulal case, it might be better to have file2 show that
it's actually grabbing the value from file1:
###
import file1
def usevar1():
print "var1 value ==", file1.var1
###
just so that someone who is reading the code understands where var1 is
coming from.
You're still learning and experimenting, so we shouldn't pound the "global
variables are evil!" mantra too much... at least, not yet. *grin*
Good luck to you!