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.

Notice that the global declaration still maps variables to the enclosing module.When nested functions are present, variables in enclosing functions may only be referenced,not changed. To clarify these points, let’s illustrate with some real code.Nested Scope ExamplesHere is an example of a nested scope:def f1( ):x = 88def f2( ):print xf2( )f1( ) # Prints 88First off, this is legal <strong>Python</strong> code: the def is simply an executable statement that canappear anywhere any other statement can—including nested in another def. Here,the nested def runs while a call to the function f1 is running; it generates a function,and assigns it to the name f2, a local variable within f1’s local scope. In a sense, f2 isa temporary function that only lives during the execution of (and is only visible tocode in) the enclosing f1.But, notice what happens inside f2: when it prints the variable x, it refers to the xthat lives in the enclosing f1 function’s local scope. Because functions can accessnames in all physically enclosing def statements, the x in f2 is automatically mappedto the x in f1, by the LEGB lookup rule.This enclosing scope lookup works even if the enclosing function has alreadyreturned. For example, the following code defines a function that makes and returnsanother function:def f1( ):x = 88def f2( ):print xreturn f2action = f1( )# Make, return functionaction( ) # Call it now: prints 88In this code, the call to action is really running the function we named f2 when f1ran. f2 remembers the enclosing scope’s x in f1, even though f1 is no longer active.Factory functionsDepending on whom you ask, this sort of behavior is also sometimes called a closure,or factory function—a function object that remembers values in enclosingscopes, even though those scopes may not be around any more. Although classesScopes and Nested Functions | 321

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

Saved successfully!

Ooh no, something went wrong!