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

Recommended Answers

All 3 Replies

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

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.

Thank you, that seemed to solve the problem.

Jusa

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.