how to count lines in a file ?

Michael Gilfix mgilfix at eecs.tufts.edu
Thu Jul 25 09:32:31 EDT 2002


  So, out of curiosity, if I define a metaclass on top of some
file object, is this still considered broken code? Is the
__del__ semantics meaningless? Would this object ever become
part of garbage collection?

  class file:
    def __init__ (self, path):
      self.file = open (path)
    def __getattr__ (self, name):
      return getattr (self.file, name)
    def __setattr__ (self, name, value):
      return setattr (self, name, value)
    def __del__ (self):
      self.file.close ()

                   -- Mike

On Thu, Jul 25 @ 10:21, Delaney, Timothy wrote:
> 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
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
`-> (tdelaney)

-- 
Michael Gilfix
mgilfix at eecs.tufts.edu

For my gpg public key:
http://www.eecs.tufts.edu/~mgilfix/contact.html




More information about the Python-list mailing list