to close or not to close?

Thomas Wouters thomas at xs4all.net
Tue Aug 1 04:54:44 EDT 2000


On Mon, Jul 31, 2000 at 08:08:59PM -0400, François Pinard wrote:
> [Thomas Wouters]

> > for x in [:256]: # or range(256) if you don't run experimental patches
> > 	open("tempfile.%d"%x)

> > Will work just fine in CPython, having open at most 2 'tempfiles' at once
> > (in an interactive session, that is, otherwise it has just 1 open.)

> I do not understand how we could have two.  Since the result of `open'
> is not saved, I presume the file will be closed immediately after being
> opened, before executing the next instruction, or the next iteration.

Hint: Here's what happens:

>>> for x in [:10]:
...     open("tmp.%d"%x, "w")
...
<open file 'tmp.0', mode 'w' at 80dba20>
<open file 'tmp.1', mode 'w' at 80dba60>
<open file 'tmp.2', mode 'w' at 80dba20>
<open file 'tmp.3', mode 'w' at 80dba60>
<open file 'tmp.4', mode 'w' at 80dba20>
[...]

In interactive mode, expressions that return something other than None, get
their return value printed *and* stored in the local variable '_'. This
variable is overwritten the next time you evaluate something that doesn't
end up as None, so it will certainly not be destroyed before the next file
is opened -- and possible long after that ;-)

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list