using 'global' across source files.

Remco Gerlich scarblac at pino.selwerd.nl
Tue Jan 2 08:59:03 EST 2001


Bram Stolk <bram at sara.nl> wrote in comp.lang.python:
> Using the 'global' keyword, I can have my functions
> access global variables, like:
> 
>   # try.py
>   val=100
> 
>   def change_val() :
>     global val
>     val = 2*val
> 
>   change_val()
>   print val
> 
> However, this scheme falls apart if I split up this
> code in two files, one containing the global, and
> one containing the func.
> 
>   # prog.py
> 
>   from funcs import *
> 
>   val = 100
> 
>   change_val()
>   print val
> 
>   # funcs.py
> 
>   def change_val() :
>     global val
>     val = val * 2
> 
> When running I get an error:
> 
> bram at gazoo> python -i prog.py
> Traceback (most recent call last):
>   File "prog.py", line 7, in ?
>     change_val()
>   File "funcs.py", line 5, in change_val
>     val = val * 2
> NameError: There is no variable named 'val'
> 
> 
> Why?

Because, at the time you imported everything from funcs.py, val didn't
exist yet. You then run change_val(), funcs.val is created, but it doesn't
get copied into every module that ever did 'from funcs import *'.

> And how can I fix this?

The best way is not to use "from module import *" at all. from...import can
be tricky, and you should only use it when you know exactly what you're
doing. If you did, you wouldn't ask this question :). Simply "import funcs"
and use "funcs.val" to access it.

An alternative is to do "from funcs import *" again after change_val(),
but that's clearly inferior in my opinion. You'd have to do it again after
every single change to val.

Don't use from...import and certainly not from...import *.

-- 
Remco Gerlich



More information about the Python-list mailing list