python function global and local scope confusion

Question:

I have a code in which I declare a variable globally. Then inside a function, when I try to use it, it gives an error Unbound variable is not declared
My code:

count_url =1

def foo():
   ...
           ttk.Label(canvas1, text=f'{varSongTitle}...Done! {count_url}/{str(var_len)}').pack(padx=3,pady=3)
        root.update()
        count_url = count_url + 1

When I read from here that for bypassing this issue: The issue as I guess was that inside function my globally declared variable was becoming local, I guess because after printing it out I was assigning it to count_url =+ That’s why I needed to also decalre it globally inside function as below:

count_url =1

def foo():
   global count_url
   ...
           ttk.Label(canvas1, text=f'{varSongTitle}...Done! {count_url}/{str(var_len)}').pack(padx=3,pady=3)
        root.update()
        count_url = count_url + 1

Now code works perfectly! But I have pair of questions How? Why?. Why it does not behave similarly if I assign global in global scope like

global count_url
count_url=1

def foo():
...

And also How can this be possible, that due to assigning inside the function a value to my global variable, why it becomes local?
ANSWER: https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.

Asked By: xlmaster

||

Answers:

The default behavior of Python is to create a new variable in the function scope without checking the global scope for a similarly named variable.

The global declaration inside the function tells Python that you want to use the variable declared in the outer scope instead of creating a new one.

Adding a reference to the official Python documentation, from a comment: https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

Answered By: Scorpio