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

  • SEARCH
  • Home
  • 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 382565
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T15:11:42+00:00 2026-05-12T15:11:42+00:00

I have some code where instances of classes have parent<->child references to each other,

  • 0

I have some code where instances of classes have parent<->child references to each other, e.g.:

class Node:

    def __init__(self):
        self.parent = None
        self.children = {}

    def AddChild(self, name, child):
        child.parent = self
        self.children[name] = child


def Run():
    root, c1, c2 = Node(), Node(), Node()
    root.AddChild('first', c1)
    root.AddChild('second', c2)


Run()

I think this creates circular references such that root, c1 and c2 won’t be freed after Run() is completed, right?. So, how do get them to be freed? I think I can do something like root.children.clear(), or self.parent = None – but what if I don’t know when to do that?

Is this an appropriate time to use the weakref module? What, exactly, do I weakref’ify? the parent attribute? The children attribute? The whole object? All of the above? I see talk about the WeakKeyDictionary and weakref.proxy, but its not clear to me how they should be used, if at all, in this case.

This is also on Python 2.4 (can’t upgrade).

Update: Example and Summary

What objects to weakref-ify depends on which object can live without the other, and what objects depend on each other. The object that lives the longest should contain weakrefs to the shorter-lived objects. Similarly, weakrefs should not be made to dependencies – if they are, the dependency could silently disappear even though it is still needed.

If, for example, you have a tree structure, root, that has children, kids, but can exist without children, then the root object should use weakrefs for its kids. This is also the case if the child object depends on the existence of the parent object. Below, the child object requires a parent in order to compute its depth, hence the strong-ref for parent. The members of the kids attribute are optional, though, so weakrefs are used to prevent a circular reference.

class Node:

    def __init__(self):
        self.parent = None
        self.kids = weakref.WeakValueDictionary()

    def GetDepth(self):
        root, depth = self, 0
        while root:
            depth += 1
            root = root.parent
        return depth


root = Node()
root.kids['one'] = Node()
root.kids['two'] = Node()

To flip the relationship around, we have something like the below. Here, the Facade classes require a Subsystem instance to work, so they use a strong-ref to the subsystem they need. Subsystems, however, don’t require a Facade to work. Subsystems just provide a way to notify Facades about each other’s actions.

class Facade:

  def __init__(self, subsystem):
    self.subsystem = subsystem
    subsystem.Register(self)


class Subsystem:

    def __init__(self):
        self.notify = []

    def Register(self, who):
        self.notify.append(weakref.proxy(who))


sub = Subsystem()
cli = Facade(sub)
  • 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-05-12T15:11:42+00:00Added an answer on May 12, 2026 at 3:11 pm

    Yep, weakref’s excellent here. Specifically, instead of:

    self.children = {}
    

    use:

    self.children = weakref.WeakValueDictionary()
    

    Nothing else needs change in your code. This way, when a child has no other differences, it just goes away — and so does the entry in the parent’s children map that has that child as the value.

    Avoiding reference loops is up high on a par with implementing caches as a motivation for using the weakref module. Ref loops won’t kill you, but they may end up clogging your memory, esp. if some of the classes whose instances are involved in them define __del__, since that interferes with the gc‘s module ability to dissolve those loops.

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

Sidebar

Related Questions

I have some code which I would like to pass instances or classes interchangeably.
I have an parent class, and several child classes. What I want is when
I have some legacy code that is creating instances of classes. I have managed
I have some javaScript Classes ( ctor+prototype methods) that I want their instances to
We have some code written in python that uses a few classes that are
In a code below, there are 2 classes, one is Node and the other
Let's say I have some classes defined as follows: class Security { Boolean AuthenticateUser(String
I have some code that creates a Process instance and later starts it. There's
I have some code using a System.Transactions.TransactionScope , that creating a new instance of
I have some object that is instantiated in code behind, for instance, the XAML

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.