reference counting and file objects

John Reese jtr at ofb.net
Tue May 17 14:50:19 EDT 2005


def uselessHash(filename):
  fp= open(filename)
  hash= 0
  for line in fp:
    hash ^= hash(line.strip())
  fp.close() # do I need this or is fp closed by ref count?
  return hash
    
Consider the function above.  Do I need the fp.close(), or will the
file be closed automatically when fp goes out of scope and its
reference count drops to zero?

If so, there's really no point in calling .close() in situations like
this where the function completes in a relatively short time,, and if
not, I should probably be using try-finally.  That's my thinking... or
the thinking of the coworker who was arguing with me.



More information about the Python-list mailing list