On 05Mar2024 20:13, Jacob Kruger <[email protected]> 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 <[email protected]>
--
https://mail.python.org/mailman/listinfo/python-list