Newbie - Variable Scope

KefX keflimarcusx at aol.comNOSPAM
Mon Nov 17 07:50:23 EST 2003


>I have a 2 Python scripts that contain the following lines:
>
>test.py
>-------
>from testmod import *
>a1 = 10
>modfunc()
>
>testmod.py
>-----------
>def modfunc():
>    print a1
>
>When I run test.py, it returns the following error:
>
>  File "testmod.py", line 2, in modfunc
>    print a1
>NameError: global name 'a1' is not defined
>
>My intent is to make a1 a global variable - so that I can access its value
>in all functions of imported modules. What should I do?
>
>Thanks in advance,
>
>Rohit

I think this is technically one script (not "two scripts"), just in two
modules, but whatever.

First off, you're using the form "from x import y", (in this case, x is
'testmod' and y is '*') which shouldn't be used for your own modules unless you
know what you're doing. It is better to write this as "import x".

This has nothing to do with the problem, though. What you have to do for your
specific test case is have testmod.py import test.py, because it uses a
variable that's defined in test.py. Using "from x import *" doesn't make the x
act like a C-style include file, though there are many similarities.

Of course, it's best to avoid situations where two modules import each other
altogether. I would put the globals in a third module and have everything
import that module. Thus, one solution would be this:

test.py
-------
import testmod
import globals

globals.a1 = 10
testmod.modfunc()


testmod.py
----------
import globals

def modfunc():
    print globals.a1


globals.py
----------
# Blank, but you can define 'a1' here instead of in test.py if it's more
appropriate


Of course, the uber-best solution is to avoid globals altogether, but that's
another thing...

- Kef





More information about the Python-list mailing list