Search code examples
pythonoopweak-references

Should a Weakref object be called every time it's accessed?


I have a class structure where the instance of one class needs to hold a reference to an instance of the other. Reading through some other posts, the best (safest) way to do this, is using weakref. It would look like this:

class ClassA:
    def __init__(self):
        self.my_b = ClassB(self)
        self.some_prop = 1

class ClassB:
    def __init__(self, some_a):
        self.some_a = weakref.ref(some_a)

The question that I have, is that to access some_prop through an instance of ClassB, you'd have call the reference which will make the object available, as per documentation:

self.some_a().some_prop

However, my question is whether calling the reference should be done every time. Can't we just call the weakref in init? I.e.

self.some_a = weakref.ref(some_a)()

and then access it (more naturally) like

self.some_a.some_prop

I have a feeling the first option is preferred, but I am trying to understand why. In my case there is no way that the referenced object gets deleted before the other.


Solution

  • For completeness' sake I will write this answer, which is a copy of @sanyash 's comment.

    Python garbage collector is clever enough to detect cyclic references and delete both objects that reference each other if there is no reference to them in the outer scope. You really don't need to use weakref.