0

I know that a global variable is created in the main scope, and to assign a value to it inside of a function, we need to use the keyword global. However, to use it (for example, to print it) inside a function, we don't need to use the keyword global. For example:

s = 5
def foo1(): 
    print(s)

s = 5
def foo2():
    global s
    s = 6
    print(s)

Now I try to do this:

s = 5
def foo3():
    print(s)
    s = 'bbb'
    print(s)

and I call foo3(). I know this is a mistake since I am trying to assign a global variable inside a function without the use of the keyword global:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo3
UnboundLocalError: local variable 's' referenced before assignment

However, I'm interested in why the first print(s) in foo3() is not executed, and I get the error when it tries to run it. How can Python recognize that s is a local variable before I even try to apply an assignment (without the keyword global)?

I hypothesise that when the function is defined, Python declares all its local variables according to the function code, and therefore it knows before the assignment that s is a local variable, and not the global. I tried to find information about this but couldn't (I'm sure there is information that I didn't see).

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Mr.O
  • 342
  • 2
  • 19
  • 2
    Does this answer your question? [Getting error when I try to print a global variable in a function in Python3](https://stackoverflow.com/questions/66225979/getting-error-when-i-try-to-print-a-global-variable-in-a-function-in-python3) – Mahrkeenerh Nov 09 '21 at 11:02
  • 1
    for better understanding of how python decides to treat if your code is referring a local or global variable, see the [answers] here(https://stackoverflow.com/questions/423379/using-global-variables-in-a-function). In short, if variable of same name appears as lvalue without the use of global, then python treats it as local variable to that function. – Anand Sowmithiran Nov 09 '21 at 11:08
  • Thank you both. I will look at this and see if I understand – Mr.O Nov 09 '21 at 11:11
  • Does this answer your question? [UnboundLocalError on local variable when reassigned after first use](https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use) – Tomerikoo Nov 09 '21 at 11:31

1 Answers1

0

When the function is defined, Python declares all its local variables according to the function code.

Not all local variables!

In my opinion, Python declares all the function's local variables which are seen inside the specific function defined or undefined keeping them separate from main variables, when you make it global, the values read or written into the variables are stored onto the main variables directly.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Pear
  • 351
  • 2
  • 12