DigviJay Patil
DigviJay Patil

Reputation: 1006

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

fileTwo.py

 import globalVar

 def fun():
    intVal = m_pTest.getInt()   # int value from m_pTest object
    print intVal

This is my short program sample when i run this it gives error in fileTwo.py in fun()

 AttributeError: 'NoneType' object has no attribute 'getInt'

Can someone explain what is wrong in this code ? Thank you!

Upvotes: 1

Views: 3465

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

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

Upvotes: 4

poke
poke

Reputation: 387587

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

# reading
print(globalVar.m_pTest)

# setting
globalVar.m_pTest = 123

Upvotes: 6

Related Questions