[docs] [issue11163] iter() documentation code doesn't work
Terry J. Reedy
report at bugs.python.org
Thu May 5 22:37:11 CEST 2011
Terry J. Reedy <tjreedy at udel.edu> added the comment:
I think this is the wrong patch for reasons given below.
The example should be replaced instead.
Readline is documented as returning '' at EOF for text files.
Iter(func,sentinel) is documented as calling func until sentinel is returned. If that never happens, it never stops. That makes it dangerous unless one KNOWS for sure that the sentinel WILL be returned or is willing to continue indefinitely. I think a sentence should be added to the doc to warn about this.
So I consider the premise of the example, "One useful application of the second form of iter() is to read lines of a file until a certain line is reached.", to be somewhat dubious. The example could be considered instead to be an example of when NOT to use the second form. This application should better be written to avoid a possible infinite loop as
with open(name) as fp:
for line in fp:
if line == sentinel:
I think a better example would be (3.2 version, use raw_input for 2.7):
return input("Enter data or return to stop: ")
for data in iter(my_input, ''):
Your alternative also works, but the above is something one might actually do. Even that is hardly much better than:
data = input("Enter data or return to stop}
if not data: break
Python tracker <report at bugs.python.org>
More information about the docs