0 votes

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
    # not freed



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

asked Sep 17, 2019 in Engine by Xrayez (1,230 points)
edited Sep 17, 2019 by Xrayez

2 Answers

+1 vote
Best answer

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.

answered Sep 17, 2019 by Zylann (26,057 points)
selected Sep 17, 2019 by Xrayez

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.

+1 vote

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

answered Sep 17, 2019 by volzhs (9,452 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.