WHY IT WORKS LIKE THAT?
I think of your problem as this:
- when you create your variable
EC
, it stay in location A in your memory.
- when you create your function
test1()
, it stay in location B.
- when you create your function
test2()
, it stay in location C.
Let say: in test2()
, you set EC
as global variable, it runs, but save that global EC
in location D, at the end of test2()
, EC
gets its value from D.
That means when you call test1()
inside test2()
, EC
that set to ec stay in A, not in D. But somehow when you print, it looks for D in your memory.
MY SOLUTION
EC = True
def test1(ec=EC):
print(ec, EC)
def test2():
global EC
EC = False
test1(ec=EC)
This is my code, and it works with Python 3.6.9
MY PROVE
To understand this, in Python there are 2 build-in functions are hex()
and id()
, so when you want to find where your variable stay in your memory you can check by hex(id(EC))
You can run your code as:
EC = True
print(hex(id(EC)))
def test1(ec=EC):
print(ec, EC)
print(hex(id(test1)))
def test2():
global EC
EC = False
print(hex(id(EC)))
test1()
print(hex(id(test2)))
You will find out that your global EC
& first EC
variable are stay in 2 different location. That's why you get the result of True False