Categories

Categories

 
 

Twitter

Twitter: @CK2go (Carsten König: Python, Astronomy, Softwaredesign)

CK2go on Twitter: @CK2go

 
 
02.12.2019
09:32

Globals are not global in Python

Well, the title already says it. Globals are module wide, not global global.... This means, that if you do

 
 
from module_b import doSomethingWithGlobalA
 
global a
a = 10
doSomethingWithGlobalA() # e.g. global a; a += 5;
 
print(a)
# a is still 10
 
 

The global would not change. This is because the global keyword only makes variables accessible to the module level - not beyond.

So if you instead of importing the module execute the file, it will run in the same context of the script calling it:

 
 
execfile('module_b.py')
 
global a
a = 10
doSomethingWithGlobalA() # e.g. global a; a += 5;
 
print(a)
# a is now 15
 
 

This will execute the files instructions in the local context and will work as (naively) expected.

To avoid confusion: best is to never mess with globals anyways... Global state is in general considered bad practice (for several reasons).

 
 
  •  
  • 0 Comment(s)
  •  

Sorry, you must be logged in to comment. Please login or register to comment.

back

 
 
Impressum