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.

However, generators allow functions to avoid doing all the work up front, which isespecially useful when the result lists are large, or when it takes a lot of computationto produce each value. Generators distribute the time required to produce the seriesof values among loop iterations. Moreover, for more advanced uses, they provide asimpler alternative to manually saving the state between iterations in class objects(more on classes later in Part VI); with generators, function variables are saved andrestored automatically.Extended Generator Function Protocol: send Versus nextIn <strong>Python</strong> 2.5, a send method was added to the generator function protocol. The sendmethod advances to the next item in the series of results, just like the next method,but also provides a way for the caller to communicate with the generator, to affect itsoperation.Technically, yield is now an expression form that returns the item passed to send,not a statement (though it can be called either way—as yield X, orA = (yield X)).Values are sent into a generator by calling its send(value) method. The generator’scode is then resumed, and the yield expression returns the value passed to send. Ifthe regular next( ) method is called, the yield returns None.The send method can be used, for example, to code a generator that can be terminatedby its caller. In addition, generators in 2.5 also support a throw(type) methodto raise an exception inside the generator at the latest yield, and a close( ) methodthat raises a new GeneratorExit exception inside the generator to terminate the iteration.These are advanced features that we won’t delve into in more detail here; see<strong>Python</strong>’s standard manuals for more details.Iterators and Built-in TypesAs we saw in Chapter 13, built-in data types are designed to produce iterator objectsin response to the iter built-in function. Dictionary iterators, for instance, producekey list items on each iteration:>>> D = {'a':1, 'b':2, 'c':3}>>> x = iter(D)>>> x.next( )'a'>>> x.next( )'c'In addition, all iteration contexts (including for loops, map calls, list comprehensions,and the many other contexts we met in Chapter 13) are in turn designed toautomatically call the iter function to see whether the protocol is supported. That’swhy you can loop through a dictionary’s keys without calling its keys method, stepthrough lines in a file without calling readlines or xreadlines, and so on:364 | Chapter 17: Advanced Function Topics

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

Saved successfully!

Ooh no, something went wrong!