Newbie - Variable Scope

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Nov 17 10:15:47 EST 2003


"RN" <rohit.nadhani at tallysolutions.com> wrote in
news:mailman.788.1069069240.702.python-list at python.org: 

> test.py
> -------
> from testmod import *

Don't use 'from testmod import *'. It will just cause confusion. Use 
'import testmod' instead.

> a1 = 10

Use: testmod.a1 = 10

You want to set a1 in the other module. If you had a global variable called 
a1 in the other module, assigning to a1 in this module would have no 
effect. They are two different variables. And that is why you don't want to 
use the 'from' variant of import, it simply assigns the value of each 
variable from testmod into an unrelated variable of the same name in the 
local module when you want to maintain a relationship between them.

> modfunc()
Use: testmod.modfunc()

> 
> testmod.py
> -----------
> def modfunc():
>     print a1

If you are going to have a variable called 'a1' in this module, it would be 
nicer to initialise it here so as to make it obvious. So add:

a1 = 0

outside the function.
> 
> 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?

By the way, a1 isn't a terribly good name for a global variable; it doesn't 
convey anything at all about the purpose of the variable. If you must use 
global variables (and you should think twice or thrice before you do), you 
should at least give them purposeful names.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list