-1

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?

2
  • 1
    like berthos said you are only importing var from sample1.py not the setting it to 10 Commented May 19, 2017 at 12:29
  • Does this answer your question? how to update global variable in python Commented Jan 6, 2023 at 16:04

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments