using 'global' across source files.

Remco Gerlich scarblac at pino.selwerd.nl
Tue Jan 2 09:49:45 EST 2001


Bram Stolk <bram at sara.nl> wrote in comp.lang.python:
> Remco Gerlich wrote:
> > 
> > Bram Stolk <bram at sara.nl> wrote in comp.lang.python:
> > >
> > > # funcs.py
> > >
> > > def change_val() :
> > >   global val
> > >   val = val * 2
> > >
> > >
> > >
> > > # prog.py
> > >
> > > val = 100
> > >
> > > import funcs
> > >
> > >
> > > funcs.change_val()
> > > print val
> > 
> > You need "print funcs.val" now (just like you call the function with
> > "funcs.change_val()).
> 
> Huh??
> Mind you, 'val' is defined in prog.py, NOT funcs.py.
> That's the whole issue I'm trying to solve.

Argh, I got confused too. Currently you have a 'val' in both modules
but they're different variables.
 
> I'm pretty confused now.
> Anyway, 'print funcs.val' does not work either, 
> besides the error happens BEFORE the print cmd, it
> happens in the function change_val(), which cannot 
> find the 'val' variable from prog.py.

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

> Nor can it find it, if I prefix it as '__main__.val'.

But

import sys
print sys.modules['__main__'].val

works ('__main__' is a string, not a module, you have to look it up first).
But this is a bit awkward.


> Well, that's my whole problem.
> How do I refer to 'val' if it is in another *unnamed* module?
> According to the manuals, it should simply be in the namespace
> '__main__', but that doesnt work either.

See above. But using globals that are shared across modules is a bit
icky anyway. Why does a named module (funcs) need to access a global in
some module that it knows nothing about? Is there a reason you need to do
this?

-- 
Remco Gerlich



More information about the Python-list mailing list