using 'global' across source files.

Mark Jackson mjackson at wc.eso.mc.xerox.com
Tue Jan 2 11:05:48 EST 2001


scarblac at pino.selwerd.nl (Remco Gerlich) writes:

> No. Right. 'val' should exist in one module only. If you want it to be in
> prog.py, funcs.py must import prog, access the variable there, and the code
> would look like this:
> 
> # funcs.py
> 
> def change_val():
>    import prog
>    prog.val = prog.val * 2
> 
> # prog.py
> 
> val=100
> import funcs
> 
> funcs.change_val()
> print val
> 
> And the other way around it would look like this:
> 
> # funcs.py
> 
> def change_val():
>    global val
>    val = val*2
>    
> # prog.py
> 
> import funcs
> funcs.val = 100
> 
> funcs.change_val()
> 
> print funcs.val

[from Bram Stolk <bram at sara.nl>]

> > Nor can it find it, if I prefix it as '__main__.val'.
> 
> But
> 
> import sys
> print sys.modules['__main__'].val
> 
> works

Not generally.  It "works" iff you use your first example as a script
('python -i prog.py'), only because this happens to create val in the
__main__ namespace.

-- 
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
	The power of accurate observation is frequently called
	cynicism by those who don't have it.
			- George Bernard Shaw





More information about the Python-list mailing list