Why this different behavior? Am I right?

Question:

I ran the following code

global_var1 = 1
global_var2 = 2

def func():
    print(global_var1)
    print(global_var2)
    global_var2 = 3

func()

It threw error

Traceback (most recent call last):
  File "/home/harish/PycharmProjects/try/scope.py", line 10, in <module>
    func()
  File "/home/harish/PycharmProjects/try/scope.py", line 7, in func
    print(global_var2)
UnboundLocalError: local variable 'global_var2' referenced before assignment

But the following code worked

__author__ = 'harish'
global_var1 = 1
global_var2 = 2

def func():
    print(global_var1)
    print(global_var2)
func()

My expectation was when the funcion func was called. It would look for global_var1 and it was not it local so it looked in global and print it.
then similarly it would look for global_var1 and it was not it local so it looked in global and print it. then it would create a variable global_var2 in localscope and assign 3 .

May be it was not done like above because then within the same functions scope the same variable global_var2 had different meaning . till line 2 it was referring to global then there after local .. Is my guess correct ?

Asked By: Harish Kayarohanam

||

Answers:

global declarations should be put inside the function:

def func():
    global global_var2
    print(global_var1)
    print(global_var2)
    global_var2 = 3

They tell python that inside the function the name global_var2 refers to the global scope instead of local. Putting a global declaration at the top level is useless.

Python doesn’t allow for the same name to refer to two different scopes inside a single scope so the assignment global_var2 = 3 imposes that the variable is local. Thus if you try to print it before it raises an error. But if you say to python that the name is actually the global name then python knows that he should take the value from that scope and assign to the global scope.

In particular:

a = 1

def f():
    print(a)
    a = 2

Here the a in print(a) and the a in a = 2 always refer to the same variable. In the above code the inside f is local because no declaration is provided and there is an assignment. So print(a) tries to access a local variable that doesn’t have a value.

If you add global:

a = 1
def f():
    global a
    print(a)
    a = 2

Now all the as in f refer to the global a, so print(a) prints 1 because it’s the value of the global variable and after executing f the value will become 2.

Answered By: Bakuriu

Python looks for local variables in functions at compile time. There is only one scope per function. So global_var2 is local, because it is defined as local variable in the last line of the function.

Answered By: Daniel
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.