Is there any notable difference between using a `weakref` vs `is_instance_valid` method?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Xrayez

Based on my little research, people suggest to use is_instance_valid in 3.1 and a weakref in 3.0. I wonder if a weakref is really that useful in 3.1.

var wr = weakref(node)
if not wr.get_ref():
    # freed
else:
    # not freed

versus:

is_instance_valid(node)

I’ve been using the latter and never the former. I wonder what are valid use cases for using a weakref.

:bust_in_silhouette: Reply From: volzhs

If I remember correctly,
weakref() has existed since 1.0
As Godot community grows, they complain it’s not obvious so is_instance_valid() came out at 3.0

:bust_in_silhouette: Reply From: Zylann

weakref is useful to hold a Reference object without contributing to its refcount.

is_instance_valid only checks if an object is valid.

You cannot only rely on is_instance_valid in the first case because in the case of Reference classes your variable would contribute to the refcount. So you’d need to store the object ID instead, which needs to be looked up each time you want the actual object, and that’s what weakref is a wrapper for.

I’ve heard about issues regarding refcount overflow, but I guess I haven’t yet dealt with it myself. Btw, I looked up the docs now, and the description has updated for WeakRef since I last checked in 2.1 and that clears up a lot of questions I’ve had… Your answer is useful for comparison with usage of is_instance_valid though.

Extending from Object would make more sense in some cases then, but one would have to free those manually. Choose your poison as they say.

Xrayez | 2019-09-17 18:53

:bust_in_silhouette: Reply From: nate00

In Godot 3.x, is_instance_valid might not be enough to detect when an object has been freed, because your reference to the freed object might return a random different (non-freed) object. Using a WeakRef instead can work around the issue, but only if your code is compatible with WeakRef not contributing the the object’s reference count.

It looks like this issue will be fixed in Godot 4.0, and is_instance_valid will be removed.