0

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).

Dmitriy Neledva
  • 867
  • 4
  • 10

1 Answers1

4

Question: Why [...] the first example works without errors but in the second example the same line of code is broken?

Because in the first example, you're only reading from a global a, then writing to a local b.

In the second example, a is assumed to be a local too (since you're not declaring global a), and it has no value when you're trying to read it in the first line, hence an error.

This is similar to JavaScript's Temporal Dead Zone, if that's familiar.

As for the question in your title:

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

You're not reassigning a global name at all in either of your examples, since indeed you're not using the global keyword. In Python, you can always read a global (or "ambient") name; otherwise it'd be a pain to e.g. use any builtin function (since they're not locals), and having a special exception for builtins would be, well, a special exception, and those aren't nice.

AKX
  • 152,115
  • 15
  • 115
  • 172