Image

Imageivorjawa wrote in Imagepython_dev

There's something I'm not understanding with lambdas here

This isn't behaving at all how I would expect:


>>> nodes = [ [1], [2], [], [4], [], [] ]
>>> nodes
[[1], [2], [], [4], [], []]
>>> lam = [(lambda : node) for node in nodes]
>>> lam[0]()
[]
>>> lam[1]()
[]
>>> lam[2]()
[]
>>> lam[3]()
[]
>>> lam[4]()
[]
>>> lam[5]()
[]
>>> 

>>> nodes = [ [1], [2], [3], [4], [5], [6] ]
>>> lam = [(lambda : node) for node in nodes]
>>> lam[0]()
[6]
>>> lam[1]()
[6]



eta
I guess I'm not the only person to have run into this:

Python’s lambda is broken!

And the hideous, absolutely insane fix is:


>>> lam = [lambda node=node: node for node in nodes]
>>> lam[0]()
[1]
>>> lam[1]()
[2]