Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8399221
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T21:14:37+00:00 2026-06-09T21:14:37+00:00

import weakref import gc class MyClass(object): def refer_to(self, thing): self.refers_to = thing foo =

  • 0
import weakref
import gc

class MyClass(object):
    def refer_to(self, thing):
        self.refers_to = thing

foo = MyClass()
bar = MyClass()
foo.refer_to(bar)
bar.refer_to(foo)
foo_ref = weakref.ref(foo)
bar_ref = weakref.ref(bar)
del foo
del bar
gc.collect()
print foo_ref()

I want foo_ref and bar_ref to retain weak references to foo and bar respectively as long as they reference each other*, but this instead prints None. How can I prevent the garbage collector from collecting certain objects within reference cycles?

bar should be garbage-collected in this code because it is no longer part of the foo–bar reference cycle:

baz = MyClass()
baz.refer_to(foo)
foo.refer_to(baz)
gc.collect()

* I realize it might seem pointless to prevent circular references from being garbage-collected, but my use case requires it. I have a bunch of objects that refer to each other in a web-like fashion, along with a WeakValueDictionary that keeps a weak reference to each object in the bunch. I only want an object in the bunch to be garbage-collected when it is orphaned, i.e. when no other objects in the bunch refer to it.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T21:14:39+00:00Added an answer on June 9, 2026 at 9:14 pm

    Normally using weak references means that you cannot prevent objects from being garbage collected.

    However, there is a trick you can use to prevent objects part of a reference cycle from being garbage collected: define a __del__() method on these.

    From the gc module documentation:

    gc.garbage

    A list of objects which the collector found to be unreachable but could not be freed (uncollectable objects). By default, this list
    contains only objects with __del__() methods. Objects that have
    __del__() methods and are part of a reference cycle cause the entire reference cycle to be uncollectable, including objects not necessarily
    in the cycle but reachable only from it. Python doesn’t collect such
    cycles automatically because, in general, it isn’t possible for Python
    to guess a safe order in which to run the __del__() methods. If you
    know a safe order, you can force the issue by examining the garbage
    list, and explicitly breaking cycles due to your objects within the
    list. Note that these objects are kept alive even so by virtue of
    being in the garbage list, so they should be removed from garbage too.
    For example, after breaking cycles, do del gc.garbage[:] to empty the
    list. It’s generally better to avoid the issue by not creating cycles
    containing objects with __del__() methods, and garbage can be examined
    in that case to verify that no such cycles are being created.

    When you define MyClass as follows:

    class MyClass(object):
        def refer_to(self, thing):
            self.refers_to = thing
        def __del__(self):
            print 'Being deleted now, bye-bye!'
    

    then your example script prints:

    <__main__.MyClass object at 0x108476a50>
    

    but commenting out one of the .refer_to() calls results in:

    Being deleted now, bye-bye!
    Being deleted now, bye-bye!
    None
    

    In other words, by simply having defined a __del__() method, we prevented the reference cycle from being garbage collected, but any orphaned objects are being deleted.

    Note that in order for this to work, you need circular references; any object in your object graph that is not part of a reference circle will be picked off regardless.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

>>> from weakref import WeakValueDictionary >>> class Foo(object): ... pass >>> foo = Foo()
import wx import wx.grid as gridlib ######################################################################## class PanelOne(wx.Panel): #---------------------------------------------------------------------- def __init__(self, parent): Constructor
import subprocess import threading import StringIO class terminal(threading.Thread): def run(self): self.prompt() def prompt(self): x
Say I derive from threading.Thread: from threading import Thread class Worker(Thread): def start(self): self.running
import time import threading class test(threading.Thread): def __init__ (self): threading.Thread.__init__(self) self.doSkip = False self.count
import sys from PyQt4 import QtGui, QtCore class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI()
Imagine I have the following situation: Test1.java import java.lang.ref.WeakReference; public class Test1 { public
import threading import weakref _mainlock = threading.RLock() _job_locks = weakref.WeakValueDictionary() def do_thing(job_id): _mainlock.acquire() #Dictionary
import actors.Actor import akka.actor.Actor._ class HelloWorldActor extends Actor { def receive = { case
Here is what I have, from a garbage-collection/proper cleanup perspective: class MyWidget(QWidget): def __init__(self,qtParent):

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.