I guess your graph contains more than one layer and the legend is not in the active layer when the error happens (I can reproduce it in such situation). You mentioned that it worked if you clicked on the legend, actually, this behavior had activated the layer with the legend. You can add the condition as following to test whether the object is valid.
out_str("found no object.");
So, please first make sure the legend is in the graph layer gl in your code.