how to count lines in a file ?

Delaney, Timothy tdelaney at avaya.com
Wed Jul 24 20:21:18 EDT 2002


> From: Richard Jones [mailto:rjones at ekit-inc.com]
> 
> Where? I'm looking at the latest library reference for file 
> objects, and it 
> makes no such statement. Unfortunately, it makes no statement 
> either way, and 
> there's a lot of art out there that takes advantage of the 
> close-on-collect 
> behaviour :(

Pay particular attention to the third paragraph below. The issue is not
whether such resources are closed when they are collected, but whether they
are collected at all.

3.1 Objects, values and types

Objects are never explicitly destroyed; however, when they become
unreachable they may be garbage-collected. An implementation is allowed to
postpone garbage collection or omit it altogether -- it is a matter of
implementation quality how garbage collection is implemented, as long as no
objects are collected that are still reachable. (Implementation note: the
current implementation uses a reference-counting scheme with (optional)
delayed detection of cyclicly linked garbage, which collects most objects as
soon as they become unreachable, but is not guaranteed to collect garbage
containing circular references. See the Python Library Reference for
information on controlling the collection of cyclic garbage.) 

Note that the use of the implementation's tracing or debugging facilities
may keep objects alive that would normally be collectable. Also note that
catching an exception with a `try...except' statement may keep objects
alive. 

Some objects contain references to ``external'' resources such as open files
or windows. It is understood that these resources are freed when the object
is garbage-collected, but since garbage collection is not guaranteed to
happen, such objects also provide an explicit way to release the external
resource, usually a close() method. Programs are strongly recommended to
explicitly close such objects. The `try...finally' statement provides a
convenient way to do this. 

Tim Delaney




More information about the Python-list mailing list