diff --git a/iterators-and-generators.html b/iterators-and-generators.html index 7c72251..7fa6971 100644 --- a/iterators-and-generators.html +++ b/iterators-and-generators.html @@ -252,6 +252,7 @@ $ $ s

Now let’s see how you can use this rules file.

[FIXME: now that this chapter comes before the I/O chapter, need to at least mention what open() does] +

[FIXME: try/finally -> with]

[download plural4.py]

import re
 
@@ -371,7 +372,7 @@ def plural(noun):
         if matches_rule(noun):
             return apply_rule(noun)
    -
  1. As you’ve seen, for line in open(...) is a common idiom for reading from a file one line at a time. But here’s what you might not know: the reason this idiom works is because open() actually returns a generator, and calling next() on this generator returns the next line of the file. +
  2. As you’ve seen, for line in open(...) is a common idiom for reading from a file one line at a time. But here’s what you might not know: the reason this idiom works is because open() actually returns an iterator, and calling next() on this iterator returns the next line of the file.
  3. No magic here. Remember that the lines of the rules file have three values separated by whitespace, so you use line.split(None, 3) to get the three “columns” and assign them to three local variables.
  4. And then you yield. What do you yield? Two functions, built dynamically with your old friend, build_match_and_apply_functions(), which is identical to the previous examples. In other words, rules() is a generator that spits out match and apply functions on demand.
  5. Since rules() is a generator, you can use it directly in a for loop. The first time through the for loop, you will call the rules() function, which will open the pattern file, read the first line, dynamically build a match function and an apply function from the patterns on that line, and yield the dynamically built functions. The second time through the for loop, you will pick up exactly where you left off in rules() (which was in the middle of the for line in file(...) loop). The first thing it will do is read the next line of the file (which is still open), dynamically build another match and apply function based on the patterns on that line in the file, and yield the two functions.