Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference

Cameron Simpson cs at cskk.id.au
Tue Mar 5 16:20:00 EST 2024


On 05Mar2024 20:13, Jacob Kruger <jacob.kruger.work at gmail.com> wrote:
>Now, what almost seems to be occurring, is that while just manipulating 
>the contents of a referenced variable is fine in this context, the 
>moment I try to reassign it, that's where the issue is occurring .

Because there are no variable definitions in Python, when you write a 
function Python does a static analysis of it to decide which variables 
are local and which are not. If there's an assignment to a variable, it 
is a local variable.  _Regardless_ of whether that assignment has been 
executed, or gets executed at all (eg in an if-statement branch which 
doesn't fire).

You can use `global` or `nonlocal` to change where Python looks for a 
particular name.

In the code below, `f1` has no local variables and `f2` has an `x` and 
`l1` local variable.

     x = 1
     l1 = [1, 2, 3]

     def f1():
         print("f1 ...")
         l1[1] = 5       # _not_ an assignment to "l1"
         print("in f1, x =", x, "l1 =", l1)

     def f2():
         print("f2 ...")
         x = 3
         l1 = [6, 7, 9]  # assignment to "l1"
         print("in f2, x =", x, "l1 =", l1)

     print("outside, x =", x, "l1 =", l1)
     f1()
     print("outside after f1, x =", x, "l1 =", l1)
     f2()
     print("outside after f2, x =", x, "l1 =", l1)

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list