3

I know what this does (makes k refer to then actual value instead of last value) but what is this syntax called? Comes from https://stackoverflow.com/a/215326/2375119

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

>>> funcs[7]()
7 # not 9
Community
  • 1
  • 1
ArekBulski
  • 4,520
  • 4
  • 39
  • 61

1 Answers1

6

The syntax has no name in particular. It's one of the ways of binding closures to their arguments; Python closures are late binding.

That syntax is a way of strapping the current iteratee value to each lambda by passing it as a default argument when creating the lambda. Since default arguments are evaluated when the function is created, the value sticks to the function.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139