Why it’s impossible to reassign global name within local scope (without `global` keyword) with using the global name’s value in reassignment?

Issue

This Content is from Stack Overflow. Question asked by Dmitriy Neledva

If we run this code

a = 1

def foo():
    b = a + 2
    print(b)
    
foo()

it works.
But if we run this code

a = 1

def foo():
    b = a + 2
    print(b)
    
    a = a + 4
    print(a)
foo()

it doesn’t work.

Question:
why in the first example b = a + 2 works without errors but in the second example the same line of code b = a + 2 is broken?
why if there is no reassignment of a we can get a from a global scope but if there is a reassignment we don’t have an access to a even if new local a doesn’t even exist yet (because the reassignment isn’t finished).



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?