def action()return spam spam 'nireturn action act normal(print(act()reallylooked up when used also prints 'nias this impliesthe enclosing scope name isn' resolved when the nested function is made--in factthe name hasn' even been assigned yet in this example the name is resolved when the nested function is called the same holds true for lambdasdef weird()spam return (lambdaspam remembers spam in enclosing scope act weird(print(act()prints so farso good the spam inside this nested lambda function remembers the value that this variable had in the enclosing scopeeven after the enclosing scope exits this pattern corresponds to registered gui callback handler run later on events but once againthe nested scope reference really isn' being resolved when the lambda is run to create the functionit' being resolved when the generated function is later called to make that more apparentlook at this codedef weird()tmp (lambdaspam spam return tmp act weird(print(act()remembers spam even though not set till here prints here againthe nested function refers to variable that hasn' even been assigned yet when that function is made reallyenclosing scope references yield the latest setting made in the enclosing scopewhenever the function is called watch what happens in the following codedef weird()spam handler (lambdaspam spam print(handler()spam print(handler()func doesn' save now prints spam looked up now prints spam looked up again now weird(nowthe reference to spam inside the lambda is different each time the generated function is calledin factit refers to what the variable was set to last in the enclosing scope at the time the nested function is calledbecause it is resolved at function call timenot at function creation time adding user-defined callback handlers