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

Python global keyword weird behaviour

def a():
    g=1
    def b():
        global g
        g=2
        def c():
            global g
            g=3
        c()
        print("c", g) #3
    b()
    print("b", g) #1 
a()
print("a", g) #3

The output is

c 3
b 1
a 3

I can’t understand why the value of g is 1 inside a() but 3 outside a()

If value of g is 3 in two places:

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

  1. after calling c()
  2. outside a().

Why is it 1 inside a()?

>Solution :

When you do g=1 in a() it creates a new local variable to that function. When you do global g in b() and c() it makes g refer to the global variable (which doesn’t yet exist when running b). So c, b and the global scope all refer to the same g (which is 3 after running c) while a refers to its local g which never changed and is still 1.

Changing global to nonlocal will make both prints of c and b to print 3, but now will make a NameError for the last print as there is no g in the global scope.

Alternatively, adding global g to the start of a, will have all three prints print 3.

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