0

I am declaring global variable in sample1.py like this and updating

sample1.py
var = 0
def foo():
    global var
    var = 10

In sample2.py I am importing this global variable

sample2.py
from sample1 import var

def foo1():
    print var

but, still it is printing "0" instead of "10". If print it in sample1.py it is printing "10".

What went wrong?

  • 1
    like berthos said you are only importing `var` from `sample1.py` not the setting it to 10 – WhatsThePoint May 19 '17 at 12:29
  • Does this answer your question? [how to update global variable in python](https://stackoverflow.com/questions/17307474/how-to-update-global-variable-in-python) – TylerH Jan 06 '23 at 16:04

3 Answers3

3

What is wrong is that the function from sample1.py is never called, ergo you variable is never initialized with 10

Correct way

Sample1.py

var = 0
def Function1:
   var = 10

Sample2.py

import Sample1
Sample1.Function1()
print(Function1.var)
Norbert Forgacs
  • 605
  • 1
  • 8
  • 27
0

Because you didn't called the function foo() in sample2.py, right now only declared the variable with 0 when you call the function foo(), then only it will update.

update sample2.py like this,

from sample1 import var,foo
foo()

def foo1():
    print var
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0

Actually, even though you have already called function foo, it won't work. Because when you use from sample1 import var, you just get a copy of sample1.var, but not really get the pointer of it. So it won't be updated when sample1.var is updated.

Sraw
  • 18,892
  • 11
  • 54
  • 87