In response to @ buchio's article Python lambda is useless ^ H ^ H ^ H ^ H ^ H difficult to use to watch.
It is easy to understand if you think that the area of local variables is reserved behind them. What you're referring to in lambda is the area, not the value of the variable (visible at the time of definition). In other words, test1 in the original article is equivalent to the following code.
>>> def test1_aux():
... env = [None]
... funcs = []
... for i in range(10):
... env[0] = i
... funcs.append(lambda a: a+env[0])
... return funcs
...
>>> print [f(10) for f in test1_aux()]
[19, 19, 19, 19, 19, 19, 19, 19, 19, 19]
The fact that the scope of the variable i is not limited to the inside of the for statement is certainly a bit confusing, but I don't think there is anything strange about it other than that.
By the way, for list comprehensions that are closely related to the for statement, variables can no longer be referenced from the outer scope from Python 3.
python2
>>> [x for x in range(3)]
[0, 1, 2]
>>> x
2
python3
>>> [x for x in range(3)]
[0, 1, 2]
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
In Python, you can call it by implementing the \ _ \ _ call \ _ \ _ method in any class. So you can use objects where you need closures.
>>> class Adder(object):
... def __init__(self, i):
... self.i = i
... def __call__(self, a):
... return a + self.i
...
>>> def test_callable():
... funcs = []
... for i in range(10):
... funcs.append(Adder(i))
... return funcs
...
>>> print [f(10) for f in test_callable()]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
In Python, it's more readable and simpler to use functions and objects, so it's more Pythonic to not use lambdas except for simple expressions.
Recommended Posts