Cameron Bell Cameron Bell - 1 year ago 78
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:


delta = 0.0

def example():
global delta

delta = 1

def ret_delta():
return delta


from b import *


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 Source

When you do

from b import *

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download