How is a global variable sustained when it's first deleted and then recreated inside a function?

Question:

I am unable to understand why the code is not showing any error when I try:

x = 2

def foo():
    global x
    del x
    x = 3

foo()
print(x)

Output: 3

I was expecting that del x would delete the reference to 2 and thus, there will not be any global variable, keeping the reference to 3 locally (accessible only within the function and not outside it).

Can someone explain what’s incorrect with my understanding of global and/or del?

Asked By: medium-dimensional

||

Answers:

import dis
print(dis.dis(foo))

you will see the bytecode which will explain

  4           0 DELETE_GLOBAL            0 (x)

  5           2 LOAD_CONST               1 (3)
              4 STORE_GLOBAL             0 (x)
              6 LOAD_CONST               0 (None)
              8 RETURN_VALUE
Answered By: Joran Beasley

Please refer to this article: why is the del statement in Python unable to delete data referenced by variables?

If I try to explain in words;
What happens with global x is whenever you refer to x inside the function namespace it looks for a similar name in global scope.

But del just deletes any name that is in function scope. In this case after deleting you assign x=3, which in turn trigger an assignment to global x.

Answered By: spramuditha
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.