@@ -1617,8 +1617,7 @@ def _break_share_link(ax, grouper):
16171617 return None
16181618
16191619 self ._axstack .remove (ax )
1620- for func in self ._axobservers :
1621- func (self )
1620+ self ._axobservers .process ("_axes_change_event" , self )
16221621 self .stale = True
16231622
16241623 last_ax = _break_share_link (ax , ax ._shared_y_axes )
@@ -1654,7 +1653,7 @@ def clf(self, keep_observers=False):
16541653 self .images = []
16551654 self .legends = []
16561655 if not keep_observers :
1657- self ._axobservers = []
1656+ self ._axobservers = cbook . CallbackRegistry ()
16581657 self ._suptitle = None
16591658 if self .get_constrained_layout ():
16601659 layoutbox .nonetree (self ._layoutbox )
@@ -1910,10 +1909,9 @@ def gca(self, **kwargs):
19101909 return self .add_subplot (1 , 1 , 1 , ** kwargs )
19111910
19121911 def sca (self , a ):
1913- """Set the current axes to be a and return a ."""
1912+ """Set the current axes to be *a* and return *a* ."""
19141913 self ._axstack .bubble (a )
1915- for func in self ._axobservers :
1916- func (self )
1914+ self ._axobservers .process ("_axes_change_event" , self )
19171915 return a
19181916
19191917 def _gci (self ):
@@ -1953,12 +1951,10 @@ def _gci(self):
19531951 def __getstate__ (self ):
19541952 state = super ().__getstate__ ()
19551953
1956- # the axobservers cannot currently be pickled.
1957- # Additionally, the canvas cannot currently be pickled, but this has
1958- # the benefit of meaning that a figure can be detached from one canvas,
1959- # and re-attached to another.
1960- for attr_to_pop in ('_axobservers' , 'show' ,
1961- 'canvas' , '_cachedRenderer' ):
1954+ # The canvas cannot currently be pickled, but this has the benefit
1955+ # of meaning that a figure can be detached from one canvas, and
1956+ # re-attached to another.
1957+ for attr_to_pop in ('canvas' , '_cachedRenderer' ):
19621958 state .pop (attr_to_pop , None )
19631959
19641960 # add version information to the state
@@ -1991,7 +1987,6 @@ def __setstate__(self, state):
19911987 self .__dict__ = state
19921988
19931989 # re-initialise some of the unstored state information
1994- self ._axobservers = []
19951990 FigureCanvasBase (self ) # Set self.canvas.
19961991 self ._layoutbox = None
19971992
@@ -2024,7 +2019,9 @@ def make_active(event):
20242019
20252020 def add_axobserver (self , func ):
20262021 """Whenever the axes state change, ``func(self)`` will be called."""
2027- self ._axobservers .append (func )
2022+ # Connect a wrapper lambda and not func itself, to avoid it being
2023+ # weakref-collected.
2024+ self ._axobservers .connect ("_axes_change_event" , lambda arg : func (arg ))
20282025
20292026 def savefig (self , fname , * , transparent = None , ** kwargs ):
20302027 """
0 commit comments