Can someone please explain why this will fail:
class A:
a = 42
b = list(a + i for i in range(10))
It fails because a
isn't in a namespace that the generator expression can see.
This works for Python2 and Python3. The lambda with the default argument is a trick to get a reference of a
in a namespace that the generator expression can see.
>>> class A:
... a = 42
... b = (lambda a=a:list(a + i for i in range(10)))()
...
>>> A.b
[42, 43, 44, 45, 46, 47, 48, 49, 50, 51]
Using a list comprehension for b
is clearer in my opinion
... b = (lambda a=a:[a + i for i in range(10)])()