I have the following python code which in my opinion behaves strangely:
Imported module:
# ChangeVar.py
def Print1():
print "1--"
def Print2():
print "2--"
Print=Print1
def Change():
global Print
Print=Print2
Main module:
#UseVar.py
from ChangeVar import *
Print()
Print()
Change()
Print()
Print()
I expect this code to print the follwing:
1--
1--
2--
2--
But what I get instead is:
1--
1--
1--
1--
Could someone point me to the right part of the python reference or explain why I don’t get the expected behavior?
Thanks,
Iulian
Python’s
globalis global to the module only.This will work, however, reconsider your use of
global– it’s universally bad practice. There should be a cleaner way to do what you want. Consider using a class inside your module.Used as so:
I would also like to note that according to the Python style guide,
lowercase_with_underscoresis the preferred naming style for functions, andlowercasefor module names.