Why no open(f, "w").write()?

John La Rooy larooy at xtar.co.nz
Sat Jun 1 03:43:50 EDT 2002


On 01 Jun 2002 19:22:32 +1200
Paul Foley <see at below> wrote:

> On Fri, 31 May 2002 22:55:04 +1200, John La Rooy wrote:
> 
> >> Well, as one of the credos of Python is that explicit is better than
> >> implicit, why are we relying on the implicit nature of file objects to close
> >> themselves? It's not nearly as easy to read.
> 
> > Do you explicitly del all your objects too, or wait for them to disappear when they go out of scope?
> 
> Neither.  You can't delete objects in Python ("del" doesn't do
> anything to objects; it does something to variables), and in theory
> they persist forever; GC is just an optimization to allow reuse of
> memory used by objects that the program will never access again,
> because you don't really have infinite memory.
> 
> Correct optimizations don't change the behaviour of correct code.
> 
> [Therefore, if the behaviour of your code does change depending on
> whether or not the optimization is done, either the optimization is
> in error or your code is.  Thus, relying on GC to close files (or do
> anything else) is Wrong.  Python really ought to print a warning when
> it GCs an open file]
> 
> -- 
> You don't have to agree with me; you can be wrong if you want.
> 
> (setq reply-to
>   (concatenate 'string "Paul Foley " "<mycroft" '(#\@) "actrix.gen.nz>"))

Good point. If I had infinite memory and was allowed an infinite number of
open files, I'd never need to close or flush my file objects, because the 
optimisation between my writing to a file and the actual event taking place
will have no effect on the behaviour of my code. But it DOES have an effect 
doesn't it? Buffering is an optimisation, isn't it?

John



More information about the Python-list mailing list