[Tutor] Re: FTP Question

Jeff Shannon jeff@ccvcorp.com
Fri, 14 Jun 2002 11:14:33 -0700


alan.gauld@bt.com wrote:

> > specifically closed it), and when this much more experienced and
> > knowledgeable person reviewed my code, he wrote:
> >
> > The following code:
> >         f = open(HTML_template_file, 'r')
> >         HTML_data = f.read()
> >         f.close()
> >  could just as easily be replace with:
> >          f = open(HTML_template_file[, 'r']).read()
>
> Then he was wrong... it should be:
>
>           HTML_data = open(HTML_template_file[, 'r']).read()
>
> and I assume the [, 'r'] bit is just to show its optionality...
>
> Personally I use the specific assignment but I do suspect
> thats just left over paranoia from my C/C++ days :-)

Actually, I think it's justified paranoia.  As I understand it, in
Jython timely finalization is not guaranteed (because it uses Java's
GC, which does not immediately clean up).  This means that the
re-coded example, with no explicit close(), leaves the file open for
some undefined length of time.  For files open for reading, this is
not so bad, but files that are written to in this way will not be
written to disk (because the buffer is never flushed) until the file
is closed, and there's no way to know when that might be (if ever -- a
program crash will kill your data without ever writing it out).

Allowing GC to implicitly close files does work in CPython, but....
while I don't envision my code running under Jython, I'd rather avoid
techniques that are known to be implementation-dependent (just as I
try to write platform-portable code as much as possible, despite that
I almost exclusively run under Windows).  And anyhow, explicit is
better than implicit.  ;)

Jeff Shannon
Technician/Programmer
Credit International