12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

def makeActions( ):... acts = []... for i in range(5): # Tries to remember each i... acts.append(lambda x: i ** x) # All remember same last i!... return acts...>>> acts = makeActions( )>>> acts[0]This doesn’t quite work, though—because the enclosing variable is looked up whenthe nested functions are later called, they all effectively remember the same value (thevalue the loop variable had on the last loop iteration). That is, we get back 4 to thepower of 2 for each function in the list because i is the same in all of them:>>> acts[0](2) # All are 4 ** 2, value of last i16>>> acts[2](2) # This should be 2 ** 216>>> acts[4](2) # This should be 4 ** 216This is the one case where we still have to explicitly retain enclosing scope valueswith default arguments, rather than enclosing scope references. That is, to make thissort of code work, we must pass in the current value of the enclosing scope’s variablewith a default. Because defaults are evaluated when the nested function iscreated (not when it’s later called), each remembers its own value for i:>>> def makeActions( ):... acts = []... for i in range(5): # Use defaults instead... acts.append(lambda x, i=i: i ** x) # Remember current i... return acts...>>> acts = makeActions( )>>> acts[0](2) # 0 ** 20>>> acts[2](2) # 2 ** 24>>> acts[4](2) # 4 ** 216This is a fairly obscure case, but it can come up in practice, especially in code thatgenerates callback handler functions for a number of widgets in a GUI (e.g., buttonpress handlers). We’ll talk more about both defaults and lambdas in the next chapter,so you may want to return and review this section later. ** In the “Function Gotchas” section for this part at the end of the next chapter, we’ll also see that there is anissue with using mutable objects like lists and dictionaries for default arguments (e.g., def f(a=[]))—becausedefaults are implemented as single objects, mutable defaults retain state from call to call, rather then beinginitialized anew on each call. Depending on whom you ask, this is either considered a feature that supportsstate retention, or a strange wart on the language. More on this in the next chapter.Scopes and Nested Functions | 325

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

Saved successfully!

Ooh no, something went wrong!