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.

Retaining enclosing scopes’ state with defaultsIn earlier versions of <strong>Python</strong>, the sort of code in the prior section failed becausenested defs did not do anything about scopes—a reference to a variable within f2would search only the local (f2), then global (the code outside f1), and then built-inscopes. Because it skipped the scopes of enclosing functions, an error would result.To work around this, programmers typically used default argument values to pass in(remember) the objects in an enclosing scope:def f1( ):x = 88def f2(x=x):print xf2( )f1( ) # Prints 88This code works in all <strong>Python</strong> releases, and you’ll still see this pattern in some existing<strong>Python</strong> code. We’ll discuss defaults in more detail later in this chapter. In short,the syntax arg = val in a def header means that the argument arg will default to thevalue val if no real value is passed to arg in a call.In the modified f2, the x=x means that the argument x will default to the value of x inthe enclosing scope—because the second x is evaluated before <strong>Python</strong> steps into thenested def, it still refers to the x in f1. In effect, the default remembers what x was inf1 (i.e., the object 88).All that’s fairly complex, and it depends entirely on the timing of default value evaluations.In fact, the nested scope lookup rule was added to <strong>Python</strong> to make defaultsunnecessary for this role—today, <strong>Python</strong> automatically remembers any values requiredin the enclosing scope, for use in nested defs.Of course, the best prescription is simply to avoid nesting defs within defs, as it willmake your programs much simpler. The following is an equivalent of the prior examplethat banishes the notion of nesting. Notice that it’s okay to call a functiondefined after the one that contains the call, like this, as long as the second def runsbefore the call of the first function—code inside a def is never evaluated until thefunction is actually called:>>> def f1( ):... x = 88... f2(x)...>>> def f2(x):... print x...>>> f1( )88Scopes and Nested Functions | 323

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

Saved successfully!

Ooh no, something went wrong!