Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Global Variable becomes local

If the title is a bit cryptic (I have no idea how to put my issue in one title) here the explanation.

I have a global variable

ex = False
orig = id(ex)

Then, I have two functions:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def start(test):
   print("Start")
   global ex
   while True:
       if id(ex) == orig:
       print("same")
   else:
       print(orig)
       print(id(ex))

def end(test):
   print("End")
   global ex
   ex = True
   while True:
       if id(ex) == orig:
       print("same")
   else:
       print(orig)
       print(id(ex))

When I enter the "end-function" the id of "ex" in the function is not the same as the original id. So, they are basically two different variables.

I do not understand why this happens. I mean, I know that it happens because I do set "ex = True" (because if I skip this line, the id is the same). But I do not understand why. I thought the idea of global keyword is exactly to make it possible to set global variables inside a function.
Using global variables in a function

>Solution :

The problem is that bools are immutual. So when you change the global variable ex, you change to where it points to (i.e., a different object). You can easily simulate that:

>>> b=True
>>> id(b)
140715296352080
>>> b=False
>>> id(b)
140715296352112
>>> id(True)
140715296352080
>>> id(False)
140715296352112

If your variable would be of a mutual type and you change a value in it, it would not change the id. In the following example I place a wrapper around the bool

>>> class MyBool():
...   val = False
...
>>> mb = MyBool()
>>> def foo():
...   global mb
...   print(id(mb))
...   mb.val = True
...   print(id(mb))
...
>>> foo()
2359703595472
2359703595472

And the id of the variable stays uncahnged.

In general, in python variables point to object in the global or local storage. When you change the "value" of a variable you need to distinguish between mutable and immutable types.

  1. When the type is mutable: the value in the memory, which is pointed by the variable is changed.
  2. When the immutable: The pointer itself is changed to a memory location that contains the new value, while keeping the old one unchanged.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading