[Python-ideas] Automatic context managers

Greg Ewing greg.ewing at canterbury.ac.nz
Sat Apr 27 02:50:47 CEST 2013


Jim Jewett wrote:
> Note that Garbage Collectors need to have a list of "roots" which can
> keep things alive, and a way of recognizing links.  If some objects
> ... use pointers that the garbage collector
> doesn't know about ... then there will be objects that
> cannot ever be safely collected.  Officially, that can be a bug in the
> object implementation, but if it leads to a segfault, python still
> looks bad.

Python's GC is more robust in this respect than traditional
mark-and-sweep collectors, because it uses the opposite
logic: instead of assuming everything is garbage unless it
can prove that it's not, it assumes that nothing is garbage
unless it can prove that it is. So if it misses a reference,
that might lead to a memory leak, but it won't cause a
crash. It also doesn't rely on "roots".

It does relies on reference counting to achieve this, however;
if something keeps a pointer to an object without increasing
its refcount, that could lead to a crash.

> Of course, if you're paying this full price anyhow, why bother paying
> the additional price of reference-counting?

In the case of CPython, it's because the cyclic GC is actually
built on top of the refcounting mechanism and wouldn't work
without it. So it's not really an additional cost at all.

-- 
Greg



More information about the Python-ideas mailing list