I have some data (in a pandas.DataFrame
), which I want to apply some filters to. I seemed proper to define a dictionary of filter functions, which for one case of filtering were supposed to be just constant comparisons, but I need flexibility of other boolean tests.
So I tried defining a filter like this.
In pure Python 3.3.5
, this works.
>>> center = {"A": 1, "B": 0}
>>> filters = {key: (lambda x: x==value)
... for key, value in center.items()}
>>> filters["A"](1)
True
In IPython 2.3.0
, using that Python 3, it works as well.
In [1]: center = {"A": 1, "B": 0}
In [2]: filters = {key: (lambda x: x==value)
...: for key, value in center.items()}
In [3]: filters["A"](1)
Out[3]: True
However, if I run this most simple test in an IPython notebook, I get
center = {"A": 1, "B": 0}
filters = {key: (lambda x: x==value)
for key, value in center.items()}
print(filters["A"](1))
print(filters["B"](1))
print(filters["A"](0))
print(filters["B"](0))
gives
False
False
True
True
Apparently, in ipython notebook
, the closure on value
does not bind the current, but the last value of value
, whereas in other python flavours, it does the opposite.
Why?