Using variables across modules

Jerry Hill malaclypse2 at gmail.com
Wed Jul 23 15:26:52 EDT 2008


On Wed, Jul 23, 2008 at 3:06 PM, Aaron Scott
<aaron.hildebrandt at gmail.com> wrote:
> ... which is what I was expecting, but not what I want. Obviously,
> each import is creating its own instance of the variable. What I need
> is a way to change myvar from within "bar.py" so that PrintVar()
> returns the new value, even though it's in a different module.

That's what happens when you do "from variables import *", it creates
those names in the local namespace.  If you just import the module,
then you can do what you want.  For example:

---variables.py---
myvar = 5
print myvar

---foo.py---
import variables
def PrintVar():
     print variables.myvar

---bar.py---
import variables, foo
print variables.myvar
variables.myvar = 2
print variables.myvar
foo.PrintVar()

---output from running bar.py---
5
5
2
2

For more on how the import statement works, see the library reference
(http://docs.python.org/ref/import.html), or maybe this article on the
various ways you can import things and the differences between them
(http://effbot.org/zone/import-confusion.htm)

-- 
Jerry



More information about the Python-list mailing list