Newbie - Variable Scope

Gonçalo Rodrigues op73418 at mail.telepac.pt
Mon Nov 17 07:55:21 EST 2003


On Mon, 17 Nov 2003 16:02:14 +0530, "RN"
<rohit.nadhani at tallysolutions.com> wrote:

>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?
>

The only truly global names in Python are the builtin ones and you
shouldn't be mucking with those unless you have a very good reason to.
Plain global variables are just global at module-level not across
modules.

To solve your problem:

- import test.py everywhere you need a1.

- Even better, reorganize your code so that you do not need global
variables in the first place.

Any more questions just holler, with my best regards,
G. Rodrigues




More information about the Python-list mailing list