[Python-Dev] Iterating a closed StringIO

Guido van Rossum guido at python.org
Fri Nov 18 16:49:55 CET 2005


On 11/18/05, Raymond Hettinger <raymond.hettinger at verizon.net> wrote:
> For Walter's original question, my preference is to change the behavior
> of regular files to raise StopIteration when next() is called on an
> iterator for a closed file.

I disagree. As long as there is a possibility that you might still
want to use the iterator (even if it's exhausted) you shouldn't close
the file. Closing a file is a strong indicator that you believe that
there is no more use of the file, and *all* file methods change their
behavior at that point; e.g. read() on a closed file raises an
exception instead of returning an empty string. This is to catch the
*bug* of closing a file that is still being used.

Now it's questionable whether ValueError is the best exception in this
case, since that is an exception which reasonable programmers often
catch (e.g. when parsing a string that's supposed to represent an
int). But I propose to leave the choice of exception reform for Python
3000.

--
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list