Python Forum
Prevent Variable Referencing - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Prevent Variable Referencing (/thread-13199.html)



Prevent Variable Referencing - Th3Eye - Oct-03-2018

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.


RE: Prevent Variable Referencing - ichabod801 - Oct-03-2018

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))



RE: Prevent Variable Referencing - buran - Oct-03-2018

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


RE: Prevent Variable Referencing - Th3Eye - Oct-03-2018

(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?


RE: Prevent Variable Referencing - buran - Oct-03-2018

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

Check the docs for functools.partial()