Best way to detect new figure in Jupyter code cell?

Hi - I’m currently working on a PR to the Reticulate package that tries to detect whether code in a Jupyter-like code cell has generated a new Matplotlib figure.

At the moment, we’re using an unsatisfying heuristic, of looking for expressions returning Matplotlib objects.

But - what is the best and recommended way to detect whether a particular cell of code has produced a new figure, and how many? I mean, wrapping code of form:

starting_figures = get_number_of_figures()
if len(get_number_of_figures()) > len(starting_figures):
    # Do something to embed plots

I know from my nb2plots days that there is matplotlib._pylab_helpers.Gcf - but the underscore there made me worry that wasn’t the best approach.