I’m trying to get my head around lambda expressions, closures and scoping in Python. Why does the program not crash on the first line here?
>>> foo = lambda x: x + a
>>> foo(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
NameError: global name 'a' is not defined
>>> a = 5
>>> foo(2)
7
>>>
Because that’s just not how Python functions work; it’s not special to lambdas:
Variables are looked up when used, not when a function is defined. They are even looked up each time the function is called, which you will definitely find unexpected if you’re coming from a C background (for example), but this isn’t a problem in Python.