Global variables in modules/functions
Peter Otten
__peter__ at web.de
Fri Nov 19 18:44:44 EST 2004
Aaron Deskins wrote:
> I'm trying to write program with a main.py and several functions
> distributed in auxiliary *.py files. I've looked through the archives on
> the 'global' keyword, but I'm still not sure how to get this right. I
> want to be able to have some variables that can be accessed/changed by
> many modules/functions.
>
> Here's an example.
>
> ____________
> main.py
> ____________
> import change
> n = 1
> change.change_n()
> print n
>
> ____________
> change.py
> ____________
> def change_n():
> global n
> n = 2
>
>
> Running main.py gives this: 1. So n is not being changed when the
> function is called. I've tried adding a 'import from main *' line to
The correct syntax is
from main import *
This will only copy the binding
n = 1
and a following
n = 2
assignment will not affect n in the main module.
> change.py, but this only gives an error message.
>
> Any ideas?
A clean way to share data between different modules is to introduce another
module and use a qualified name to access data in that module:
shared.py
n = 1
main.py
import shared
import change
change.change_n()
print n
change.py
import shared
def change_n():
shared.n = 2
However, I'm not convinced that you really need that kind of global data at
all:
main.py
import change
n = 1
n = change.change_n()
print n
change.py
def change_n():
return 2
is clearly a superior design.
Finally, what you originally requested is not impossible, just bad:
change.py
import sys
def change_n():
sys._getframe(1).f_globals["n"] = 2
Peter
More information about the Python-list
mailing list