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?