What are the best ways to use a value of a nonlocal variable defining a function in Python?

Viewed 14

So, I've got a case: I need to define a function and use a global variable, which stores a value which can be changed over the time.

For example:

functions = []

for i in range(2):
    outer_variable = [i]
    def inner_function():
        print(outer_variable)
    functions.append(inner_function)


functions[0]()
functions[1]()

It looks right. And expected output is [0] [1]. But actually it will take the last value of i, and the output will be [1] [1].

I've come up with using closures, but it looks bulky:

for i in range(2):
    def closure(number):
        outer_variable = [number]
        def inner_function():
            print(outer_variable)
        return inner_function
    functions.append(closure(i))

Another solution: use default values for function parameters:

for i in range(2):
    outer_variable = [i]
    def inner_function(number=outer_variable):
        print(number)
    functions.append(inner_function)

But in this case IDE warns me that I try to use mutable value as default. So it doesn't seem like a proper way as well.

Do I miss some neat way to implement this?

0 Answers
Related