Python Forum

Full Version: Prevent Variable Referencing
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I don't know how to explain it very well, but I've been trying to figure this out for a few days and I haven't had any luck with fixing it.

The following code is supposed to append a lambda to a list, so that the function the lambda calls can be called later on. NOTE: this isn't my actual code, but a proof of concept that works in the same way.
def foo(bar):
	print(bar)

li = []

for i in range(10):
	li.append(lambda: foo(i))
Later I can call the functions using this chunk of code.
for func in li:
	func()
When I run this, instead of steadily incrementing, it just uses the last value of i.
Output:
9 9 9 9 9 9 9 9 9 9
I understand that this is due to how python handles variable referencing, but I want to know if there is a way to bypass this and only get the value of i without referencing it.
You do this by having a function return a function.

def foo(bar):
    def sub():
        print(bar)
    return sub
 
li = []
 
for i in range(10):
    li.append(foo(i))
from functools import partial
def foo(bar):
    print(bar)
 
li = []
 
for i in range(10):
    li.append(partial(foo, i))

for func in li:
    func()
Output:
0 1 2 3 4 5 6 7 8 9
but it's weird what you are doing
(Oct-03-2018, 04:56 PM)buran Wrote: [ -> ]
from functools import partial
def foo(bar):
    print(bar)
 
li = []
 
for i in range(10):
    li.append(partial(foo, i))

for func in li:
    func()
Output:
0 1 2 3 4 5 6 7 8 9
but it's weird what you are doing

Can you explain what partial() does?
(Oct-03-2018, 06:58 PM)Th3Eye Wrote: [ -> ]Can you explain what partial() does?

Check the docs for functools.partial()