D
Donn Cave
"Rainer Deyke said:Which leads us back to having to manually close files.
I DON'T want to manually close files. I DON'T want to deal with the
limitations of with-open-file. And, here's the important bit, I DON'T WANT
TO COMBINE OR CHOOSE BETWEEN THESE TWO METHODS, BOTH OF WHICH ARE FLAWED.
What I want to open a file and have it close automatically when I am done
with it. I can do that in C++. Why can't I do it in Python?
None of the above makes a whole lot of sense to me, and judging
by the use of upper case I'm inclined to believe that discussing
this with comp.lang.lisp participants has caused you to become
disturbed. I am accordingly posting this only to comp.lang.python.
You can have files close automatically in Python, but automatically
isn't by itself a rather vacuous term, and `when I am done with it'
doesn't help a bit. In C Python, when a file object is no longer
referenced by any part of the program, it closes. If it's local
to a function, including bound only to a function parameter or some
such thing, that will occur when control returns from the function.
Unless the file becomes involved in a circular reference, in which
case the close will be deferred until the references are discovered
and broken by the garbage collector. Unless the garbage collector
is unable to do so because of some property of the members, such as
a __del__ method.
No doubt there is a great deal of C++ arcana that I have missed out
on, but the basic finalization issues are the same as far as I know.
C++ programmers aren't subject to the above exceptions only because
they don't get any of the functionality to which these are exceptions!
Function local objects are always deleted on return from the function
regardless - and any other part of the program that retains a pointer
to such an object will become unsound. Objects allocated on the heap
have to be deleted explicitly, after which other parts of the program
that reference them will become unsound. If you do a fraction of the
explicit management that C++ requires, you can get reliable finalization.
I am not familiar with with-open-file, but I imagine if you decide to
write your software in Lisp, you will probably want to give it a try.
There is also nothing wrong with closing a file explicitly. There are
reasons for it that have nothing to do with the language, and then there
is a school of thought (actually the party line for Python) that says
you should explicitly close files in any case because the memory
management rules are different for Java Python and could in theory
change in a later release of C Python. Apparently Java's finalization
is not immediate.
Donn Cave, (e-mail address removed)