Anonymous file closing

Donn Cave donn at drizzle.com
Sat Jun 12 11:07:50 EDT 2004


Quoth Duncan Booth <me at privacy.net>:
| surferjeff at gmail.com (Jeff) wrote in
| news:781dd16f.0406111108.6f2e1afd at posting.google.com: 
| ...
|>> > text = open(filename, 'r').read()
| ...
|>> If you aren't worried about portability, and you are using the C 
|>> implementation of Python then you may find it is closed immediately
|>> but it is poor practice to depend on it.
|> 
|> This is true, but I recommend:
|> 
|> 1. Only use the C implementation of Python, a.k.a. The Implementation.
|> 2. Depend on the file being closed immediately in this case.  If the
|> authors of the C implementation ever changed this behavior, they would
|> break *lots* of existing python code, and they would also break one of
|> the nicest example of how Python just works.
|
| Any existing Python code which depends on the file always being closed here 
| is wrong today. If the read method raises an exception the file will not be 
| closed until the exception traceback object has been cleared and that could 
| be a long time.

Well, we may be getting into a semantic tight spot here.  What does
`depend on' mean?  I think a reasonable interpretation is that normal
files may be opened and read as shown above without concern about using
up file descriptors, holding files open and preventing them from being
effectively deleted, etc.

That is, in fact, true.  In an ordinary Python application, it would be
silly to bundle that kind of thing up in try/finally blocks, and bog the
code down in clutter over something that really just works.

If some particular case comes up where the application should `depend on'
a particular close in a more critical sense, that's different, but that's
not the picture I get from the example.  The only bad practice issue is
Java Python.

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list