0

I had read two other question about it. this

But i dount understand this behavior:

#mod1 __init__.py
g = 5

#mod2 __init__.py
from mod1 import g
def bar():
    print g

#main1.py
import mod1
mod1.g = 10
from mod2 import bar
bar() # prints 10

#main2.py
from mod1 import g
g = 10
from mod2 import bar
bar()

So question is why main1 prints 10 and main2 prints 5? What is the real difference between from import and import?

Heidll
  • 3
  • 4

2 Answers2

1

this has to do with scope

mod2 imports mod1 (g=5)

main1 sets mod1.g to ten, and asks mod2 to print the value of mod1.g

main2 sets main2.g to ten, but mod1.g is unchanged

Mohammad Athar
  • 1,953
  • 1
  • 15
  • 31
0

The point is that in main1() you set the variable g in the module mod1 to 10, so calling bar() returns 10. I think thats clear. In main2() you first set g to 10, but when mod2 imports mod1, it gets a fresh scope with an initial set of variables. Try to print g in main2() after calling mod2, I guess it will print the changed value (10).

You must keep in mind, that import just tells the interpreter to look up whatever is called in the corresponding module (as if you would open your script again). Of course the value assigned to a variable does not change in your script when the variable is changed by your program. The interpreter reads the .py file only once (and in your case once again), that is when importing it.

Sim Son
  • 310
  • 1
  • 10