2

I discovered this weird and interesting bahaviour while using matplotlib. I wrote a simple animation for demonstration purpose:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation


fig, ax = plt.subplots()
line, = ax.plot(range(10))


def func(i=0):
    line.set_ydata(np.random.rand(10) * 10)
    return line


ani = animation.FuncAnimation(
    fig=fig,
    func=func,
    frames=np.linspace(0, 4 * np.pi, 300),
)
plt.show()

It works as expected, and nothing strange happens.

But if I change the line to:

animation.FuncAnimation(
    fig=fig,
    func=func,
    frames=np.linspace(0, 4 * np.pi, 300),
)

It stops working, and func would never be called.

So, why saving the ani object makes the differences even it's never referenced? And how does matplotlib even know whether I did that?

================

Just after I finished writing this, the garbage collector sprang up in my mind. But I don't know how the gc works, and several tests didn't convince me.

Besides, I wonder:

Are similar behaviors common in other libraries? I think we call a function either to "to something" or to "get the returned value or object", so the FuncAnimation seems strange to me. Am I feeling right?

user17
  • 331
  • 3
  • 11
  • It is not strange at all that a reference to a class instance needs to be kept. In fact this is almost always the case, because if you wanted to throw away your object directly after creation, you would rarely even create that object in the first place. – ImportanceOfBeingErnest Feb 16 '18 at 11:12

1 Answers1

2

FuncAnimation is a class, not a function. You need to indeed keep a reference to the class instance in order to prevent it from being garbage collected.

This is also one of the first sentences in the animation documentation

In both cases it is critical to keep a reference to the instance object. The animation is advanced by a timer (typically from the host GUI framework) which the Animation object holds the only reference to. If you do not hold a reference to the Animation object, it (and hence the timers), will be garbage collected which will stop the animation.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
Dennis Soemers
  • 8,090
  • 2
  • 32
  • 55