Guest123
Guest123

Reputation: 105

Setting global variable across files in python

I want to set the value of a global variable x in file p2.py. Then, this value is to be used in p1.py. However, the value of x is not getting changed in p1.py. I have tried using global keyword.
Could anyone tell me what is wrong in this code:

p2.py

x=''
def set_vals():
   global x
   x='a'

p1.py

from p2 import *
set_vals()
global x 
print x

Thanks

Upvotes: 3

Views: 3039

Answers (1)

Jug
Jug

Reputation: 550

Once you have imported from p2 import *, you get a copy of the x which is local to p1. This is not the exact same x as in p2... its now a local variable 'x' in p1 which is also pointing to the same object as the 'x' in p2.

The p2.x and the x in p are both references to the same entity immediately after import p2. However, when you run set_vals(), it only changes the value of x (repoints the pointer) inside the p2 module. The x inside the p1 module remains pointing to the old thing.

The set_vals function and its global x are still part of the p2 module, even though they have been imported into p1. Hence, they will affect the value of x in p2 only. This happens because functions remember the scope that they are created in (read about closures to learn more).

You can try this, which will do what we expect...

import p2
print p2.x
p2.set_vals()
print p2.x  # p2.x will change

What your code is equivalent to...

import p2
x = p2.x
set_vals = p2.set_vals
del p2

set_vals()   # changes p2.x
global x
print x     # this and p2.x are not same anymore

Its clear that the x in p1 is a separate variable that's initially pointing to the same object as the 'x' in p2. Changing the p2.x pointer is is not going to change what x in p1 is pointing to. 'x' in p1 keeps pointing to the same thing as it initially was.

Upvotes: 3

Related Questions