Global and Local Variables in Python


#1

Hi,

I am having trouble understanding why the snippet of code does not run when the global x line is REMOVED. Here’s my reasoning. When global x is removed, increase() looks for a local variable x, that has not been declared in the function. So it looks for a global variable x which exist and is equal to 1. So increase() makes a local variable named x and its value is 1 (the global variable x) + 1 = 2. So increase() prints 2. Finally the last print(x)) prints 1 because it refers to the global variable x = 1, not local variable x = 2 which is not accessible outside increase(). Where have I gone wrong? Thanks.

38 PM


#2

Hi @coursecoder30879,

The occurrence of an assignment to a variable within a function establishes the existence of a local variable of the specified name, unless that name was declared within the function as global. That happens even before the expression to the right of the assignment operator is evaluated. The local scope of the name even applies to statements that occur prior to the first assignment to that name. Therefore, prior to evaluation of the expression to the right of the assignment, any reference to the name of the new variable refers to the local one.

Accordingly, if x is not declared as global in your increase function, Python tries to create a local x within that function based on the assignment statement. However, the assignment that you have provided also requires lookup of an x, and it fails because the new local x does not yet have a value within that function.

Check this out …

x = 7
def xf():
    print(x)
    x = 9

xf()

Output …

Traceback (most recent call last):
  File "/Users/glennrichard/Documents/xf.py", line 6, in <module>
    xf()
  File "/Users/glennrichard/Documents/xf.py", line 3, in xf
    print(x)
UnboundLocalError: local variable 'x' referenced before assignment

See What are the rules for local and global variables in Python?

Edited several times for clarification of the explanation on December 24, 2017


#3

In short, variables in a function are created when the function itself is created (not when it’s called)
And they’re unreadable until they’ve been assigned, but will still prevent fallback to globals

(Reason: it’s faster to skip checking whether the variables are there or not)


#4

Yes, that is an essential part of the situation.

Imo, it’s also best that the status of the scope of the name is uniform within the function, rather than to have it change dynamically - less bug-prone.


#5

Great. Thanks appylpye and ionathan! Merry Christmas!


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.