Skip to content Skip to sidebar Skip to footer

Global Variable Is Not Updating In Python

I have 3 files. globalVar.py global m_pTest m_pTest = None FileOne.py import globalVar import fileTwo m_pTest = Class.getOutput() # Value is assigne fileTwo.fun() #Do anything f

Solution 1:

global m_pTest doesn’t make a variable magically global; instead it sets the name m_pTest in the current scope to refer to a global variable (from outer scope). So placing it in globalVar.py does basically nothing.

If you wanted to import only the variable, you could use the following:

from globalVar import m_pTest

However, when setting m_pTest to a different value, you will not affect the original object that was created in globalVar.py so the change isn’t seen elsewhere.

Instead, you have to import globalVar as normal, and then refer to m_pTest as a member of that module:

import globalVar

# readingprint(globalVar.m_pTest)

# setting
globalVar.m_pTest = 123

Solution 2:

Why using a global at all ?

# FileOne.py
import fileTwo

value = Class.getOutput() 
fileTwo.fun(value)
#Do anything

# fileTwo.py
def fun(value):
    intVal = value.getInt()   
    print intVal

Post a Comment for "Global Variable Is Not Updating In Python"