closing file

Jeff Epler jepler at unpythonic.net
Tue Apr 20 11:32:12 EDT 2004


A file object is automatically closed by its destructor.  In CPython,
an object's destructor (a method called __del__) is called when its
refcount equals zero.  This rule is a little different in Jython, and
the rule I just gave also doesn't explain what happens when there is a
cycle (A holds a reference to B holds a reference to A).

In both examples below, there is a single reference to the recently
created Marcello object, which has the single reference to a Noisy
object.  So when m is deleted (explicitly or implicitly), the refcount
of the Noisy instance m.o also drops to zero and its __del__ is called.

The opened file in your original example would be closed at the same
times as Noisy prints "del".

Jeff

class Noisy:
    def __del__(self):
        print "del"

class Marcello:
    def f(self):
        self.o = Noisy()

print "Example 1: using del to collect objects"
m = Marcello()
m.f()
del m

print "Example 2: the locals of a function are implicitly deleted at return"
def g():
    m = Marcello()
    m.f()
g()




More information about the Python-list mailing list