0

I have encountered a problem with variables which I have defined in a module and then manipulating them from other modules.

I have something like this in moduleA.py:

gVar = None

def getVar():
    return gVar

def setVar(val):
    gVar = val

Then, in moduleB.py I have this:

import moduleA #I also want to get rid of this import...
from moduleA import* #...and use only this import

print getVar() #prints "None"

setVar(10)
print getVar() #prints "None" <-- wrong!

moduleA.gVar = 10
print getVar() #prints "10"

How can I make it so that setVar() actually modifies the variable defined in moduleA.py?

Thanks for help,
Jusa

3
Contributors
3
Replies
4
Views
10 Years
Discussion Span
Last Post by Jusa
0

You need to set gVar global in function setVar(), so it will be visible for function getVr():

gVar = None

def getVar():
    return gVar

def setVar(val):
    global gVar
    gVar = val
0

Hi, you can do so as said earlier making the variable global.

here is ur code, I modified..

# moduleA.py
global gVar
gVar = 'moduleA'

def getVar():
    global gVar
    return gVar

def setVar(val):
    global gVar
    gVar = val
#moduleB
from moduleA import* 

print getVar() 
setVar(10)
print getVar() 

moduleA.gVar = 10
print getVar()

kath.

0

Thank you, that seemed to solve the problem.

Jusa

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.