Strange unknown lambda syntax

I know what it does (makes it a k

reference to the actual value instead of the last value), but what is this syntax called? Comes from StackOverflow question.

funcs = [] 
for k in range(10):
     funcs.append(lambda k = k: k)

>>> funcs[7]()
7 # not 9

      

+3


source to share


1 answer


The syntax has no particular name. This is one way to bind closures to their arguments; Closing Python is late binding .



This syntax is a way to bind the current value of the iterate to each lambda

one by passing it as the default argument when creating the lambda. Since the default arguments are evaluated when the function is created , the value is bound to the function.

+6


source







All Articles