I wanted to make multiple variants of a function with some different default parameters, but it didn't work good at all.
Here's a simplified example:
In [1]: def showme(what):
...: print("My number is %d!" % what)
...:
In [2]: showme(99)
My number is 99!
In [3]: fns = []
In [4]: for i in range(0, 10):
fns.append( lambda: showme(2**i) )
In [5]: for fn in fns:
fn()
My number is 512!
My number is 512!
My number is 512!
My number is 512!
My number is 512!
My number is 512!
My number is 512!
My number is 512!
My number is 512!
My number is 512!
In [6]:
What am I doing wrong, and how can I fix it? Obviously I expected 1,2,4,8...
.
In the actual code, the lambda also gets some other arguments, not just i
.
When I used hard-coded numbers, it worked like charm.