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.

f.next( )'print sys.path\n'>>> f.next( )'x = 2\n'>>> f.next( )'print 2 ** 33\n'>>> f.next( )Traceback (most recent call last):File "", line 1, in f.next( )StopIterationThis interface is exactly what we call the iteration protocol in <strong>Python</strong>—an object witha next method to advance to a next result, which raises StopIteration at the end ofthe series of results. Any such object is considered iterable in <strong>Python</strong>. Any suchobject may also be stepped through with a for loop or other iteration tool because alliteration tools work internally by calling next on each iteration and catching theStopIteration exception to determine when to exit.The net effect of this magic is that, as mentioned in Chapter 9, the best way to read atext file line by line today is not to read it at all—instead, allow the for loop to automaticallycall next to advance to the next line on each iteration. The following, forexample, reads a file line by line (printing the uppercase version of each line alongthe way) without ever explicitly reading from the file at all:>>> for line in open('script1.py'): # Use file iterators... print line.upper( ),...IMPORT SYSPRINT SYS.PATHX = 2PRINT 2 ** 33This is considered the best way to read text files by lines today, for three reasons: it’sthe simplest to code, the quickest to run, and the best in terms of memory usage.The older, original way to achieve the same effect with a for loop is to call the filereadlines method to load the file’s content into memory as a list of line strings:>>> for line in open('script1.py').readlines( ):... print line.upper( ),...IMPORT SYSPRINT SYS.PATHX = 2PRINT 2 ** 33This readlines technique still works, but it is not best practice today, and performspoorly in terms of memory usage. In fact, because this version really does load theentire file into memory all at once, it will not even work for files too big to fit into thememory space available on your computer. On the other hand, because it reads oneline at a time, the iterator-based version is immune to such memory-explosion issues.Iterators: A First Look | 261

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

Saved successfully!

Ooh no, something went wrong!