12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

If you avoid nesting this way, you can almost forget about the nested scopes conceptin <strong>Python</strong>, unless you need to code in the factory function style discussed earlier—atleast for def statements. lambdas, which almost naturally appear nested in defs, oftenrely on nested scopes, as the next section explains.Nested scopes and lambdasWhile they’re rarely used in practice for defs themselves, you are more likely to careabout nested function scopes when you start coding lambda expressions. We won’tcover lambda in depth until Chapter 17, but, in short, it’s an expression that generatesa new function to be called later, much like a def statement. Because it’s anexpression, though, it can be used in places that def cannot, such as within list anddictionary literals.Like a def, alambda expression introduces a new local scope. Thanks to the enclosingscopes lookup layer, lambdas can see all the variables that live in the functions inwhich they are coded. Thus, the following code works today, but only because thenested scope rules are now applied:def func( ):x = 4action = (lambda n: x ** n)return action# x remembered from enclosing defx = func( )print x(2) # Prints 16, 4 ** 2Prior to the introduction of nested function scopes, programmers used defaults topass values from an enclosing scope into lambdas, as for defs. For instance, the followingworks on all <strong>Python</strong> releases:def func( ):x = 4action = (lambda n, x=x: x ** n)# Pass x in manuallyBecause lambdas are expressions, they naturally (and even normally) nest insideenclosing defs. Hence, they are perhaps the biggest beneficiaries of the addition ofenclosing function scopes in the lookup rules; in most cases, it is no longer necessaryto pass values into lambdas with defaults.Scopes versus defaults with loop variablesThere is one notable exception to the rule I just gave: if a lambda or def definedwithin a function is nested inside a loop, and the nested function references anenclosing scope variable that is changed by the loop, all functions generated withinthat loop will have the same value—the value the referenced variable had in the lastloop iteration.For instance, the following attempts to build up a list of functions that each rememberthe current variable i from the enclosing scope:324 | Chapter 16: Scopes and Arguments

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!