Cameron Bell Cameron Bell - 4 months ago 8
Python Question

Python multi module global variables. A bug in python?

Recently I set up this example and am surprised by the results. I will demonstrate this with code:

File1: b.py:

delta = 0.0

def example():
global delta

delta = 1

def ret_delta():
return delta


File2: a.py:

from b import *

example()

#WHY ARE THESE DIFFERENT?
print(delta) # prints: 0.0
print(ret_delta()) # prints: 1


This doesn't make sense! Why would accessing the variable and calling a function that returns that variable make any difference?

For your reference I am using python 3.5.2 on Windows 32 bit

Answer

When you do

from b import *

in a.py, delta is imported into the module a. As float in an immutable type in Python, a.delta becomes a completely separate variable from b.delta, i.e. it points to a different value. Thus, the first print() prints the initial value of a.delta, while the second prints the updated value of b.delta.