Newbie Newbie, we are all Newbie to something
Gordon McMillan
gmcm at hypernet.com
Fri Feb 25 09:01:34 EST 2000
Gregoire Welraeds wrote:
> I'm currently reading the Python Reference Manual and I got a small
> question regarding the __del__() statement in a class definition.
> I understand his utility when you don't have a garbage collector and
> memory management. In this case, it is important to have del statement to
> free object properly.
No, the __del__ method (if it exists) is called when Python is
about to dealloc the object because the refcount has dropped
to zero. If you code a __del__, it's to release some resource
that won't be automatically reclaimed.
But what if you have ?
> In the same topic, do we have to explicitly close an open file before
> exiting:
No. File objects close themselves when dealloc'ed. So this is
a common idiom in Python:
text = open(filenm, 'r').read()
With both GC (at least, most implementations) and refounting
you have problems with circular references. In (most) GC,
when a unreachable cycle of objects is reclaimed, the
finalizers are not called, but the memory is reclaimed. With
refcounting, unreachable cycles live forever.
But, with refcounting, when a refcount reaches 0, the object is
deallocated then and there, so it is safe to release resources
in the dealloc (or __del__). In GC, there are any number of
factors that can influence when the finalizer is run, so you
normally code an explicit close method if you need the
resource released in a timely manner.
- Gordon
More information about the Python-list
mailing list