Populating a list

David Bolen db3l at fitlinxx.com
Tue Dec 11 03:48:07 CET 2001


Jeremy Whetzel <lists at toadmail.com> writes:

> Ahhhh... I got it.  Thank you.  I really thought it closed the file
> because of the readlines() on the end of the 'open' function.  *scurries
> off to fix current project*

Yes it is closing the file (except delayed perhaps in the case of an
exception as noted elsewhere in this thread), and yes it's related to
the use of the readlines() method.  At least in the CPython
implementation of Python that uses reference counting (the same would
not hold true for Jython).

While I personally think handling explicit file closes is better, in a
statement such as:

	f = open('filename').readlines()

in the CPython implementation of Python which uses reference counting,
the open() call returns a file object.  A reference to this object
only exists within the expression as a temporary reference.  That
reference is then used to call the readlines() method of the file
object.  That method executes, the result of which is an object (a
list of lines in this case) which you then store a reference to as
'f'.

When the statement completes, all that is left is 'f' bound to the
object returned by the readlines() call.  The temporary reference to
the file object disappears as it only existed for the duration of the
expression.  At that point there are no further references to the file
object returned by open(), so in the reference counted implemented,
the reference count for the object goes to zero, and the object is
destroyed.  During the destruction of a file object, the file is also
closed.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list