Can python clear two object cited each other?

Alex Martelli aleaxit at
Wed Jun 6 10:08:13 EDT 2001

"XiaoQin Xia" <XQ.Xia at> wrote in message
news:3B1E2D99.8ED4DE6A at
> Hi, everybody,
> Can python clear two object cited each other?

Yes.  This is called a "reference loop", and
since Python 2.0 it can be cleared up by garbage
collection ***IF*** (crucial!) the objects
involved have no __del__ method.  (The __del__
methods might have to be called at "funny" times
to break up the refloop... so objects having
them do get collected but not cleared up... see
the gc module for more info).

> for example:
> class A:
>     def __init__(self, obj=None):
>         self.mine=obj
>         if obj:
>             obj.mine=self
> a=A() # create a object instance, say OA, referenced by variable a
> b=A(a)  # create another instance, say OB. so OB is referenced by both
variable b and instance OA
>             # and OA is referenced by a and OB
> del a  # this line is able to delete variable a, instead of the OA, which
is still refereced by OB
> del b # this line is able to delete b, instead of OB, which is still
referenced by OA
>  # so the OA and OB is still in memory, whether I have to write a method
for class A if I want to clear its intances from memory?

Just let gc do its job, or if you want to
control deletion times
    import gc
and call the gc functions appropriately.

If you *DO* need __del__ methods on your
types it's much harder -- but Python 2.1
eases it by letting you define *weak*
references that go away rather than
keeping the referred-object alive, so
that's another option.

But generally doing finalization explicitly
(in try/finally, with .close() methods, etc)
is preferable in Python.  So, if you can, do
away with the __del__ methods, and just let
gc work (automatically in most cases, under
your control if you have very special needs).


More information about the Python-list mailing list