I'm learning Python as my 1st language from http://www.diveintopython3.net/. On Chp 7, http://www.diveintopython3.net/iterators.html, there is an example of how to use an iterator.
import redef build_match_and_apply_functions(pattern, search, replace):def matches_rule(word):return re.search(pattern, word)def apply_rule(word):return re.sub(search, replace, word)return [matches_rule, apply_rule]class LazyRules:rules_filename = 'plural6-rules.txt'def __init__(self):self.pattern_file = open(self.rules_filename, encoding='utf-8')self.cache = []def __iter__(self):self.cache_index = 0return selfdef __next__(self):self.cache_index += 1if len(self.cache) >= self.cache_index:return self.cache[self.cache_index - 1]if self.pattern_file.closed:raise StopIterationline = self.pattern_file.readline()if not line:self.pattern_file.close()raise StopIterationpattern, search, replace = line.split(None, 3)funcs = build_match_and_apply_functions(pattern, search, replace)self.cache.append(funcs)return funcsrules = LazyRules()def plural(noun):for matches_rule, apply_rule in rules:if matches_rule(noun):return apply_rule(noun)if __name__ == '__main__':import sysif sys.argv[1:]:print(plural(sys.argv[1]))else:print(__doc__)
My question is: how does the 'for matches_rule, apply_rule in rules:' loop in the plural(noun) function know when to exit after fulfilling the if condition? There are no StopIteration commands for that condition. I would expect the for loop to continue until the rules.cache is iterated completely.
Thank you for the help!