pythonfunctionvariable-binding

Python: function defined in while loop refers to old variable


I have a function that I define in a while loop that is called by code I do not control.

In the following example, access() always returns the value 1. Why? And how can I make access() return the latest value?

while True:
    g = [1,2,3]

    def access():
        return g[0]

    print(access())
    g[0] += 1

The same seems to be true for lambdas. I cannot make g global.


Solution

  • Because the g variable is always reinitialized to [1,2,3].

    Just move it outside the while loop.

    g = [1,2,3]
    while True:
        .....