Understanding a global variable in Python

I ran into a strange problem in Python when using global variables.

I have two modules (files): mod1.py and mod2.py

mod1 trying to change the global variable var defined in mod2 . But var in mod2 and var in mod seem to be two different things. Thus, the result shows that such a modification does not work.

Here is the code:

 #code for mod2.py global var var = 1 def fun_of_mod2(): print var #code for mod1.py from mod2 import var,fun_of_mod2 global var #commenting out this line yields the same result var = 2 #I want to modify the value of var defined in mod2 fun_of_mod2() #but it prints: 1 instead of 2. Modification failed :-( 

Any hint on why this is happening? And how can I change the value of val defined in mod2 to mod1 ?

thanks

+6
source share
1 answer

When you import var into mod1 :

 from mod2 import var,fun_of_mod2 

You give it the name var in the mod1 namespace. It is as if you did this:

 import mod2 var = mod2.var fun_of_mod2 = mod2.fun_of_mod2 del mod2 

In other words, there are now two names for the value, mod1.var and mod2.var . They match at first, but when you reassign mod1.var , mod2.var still points to the same thing.

What you want to do is simply:

 import mod2 

Then select and assign the variable as mod2.var .

It is important to note that global variables in Python are not truly global. They are global only for the module in which they are declared. To access global variables inside another module, you use the module.variable syntax. The global operator can be used inside a function that allows you to assign a global-global name (without it, assigning a variable makes it a local variable in this function). This has no other effect.

+11
source

Source: https://habr.com/ru/post/917281/


All Articles