@@ -1622,8 +1622,7 @@ def _break_share_link(ax, grouper):
1622
1622
return None
1623
1623
1624
1624
self ._axstack .remove (ax )
1625
- for func in self ._axobservers :
1626
- func (self )
1625
+ self ._axobservers .process ("_axes_change_event" , self )
1627
1626
self .stale = True
1628
1627
1629
1628
last_ax = _break_share_link (ax , ax ._shared_y_axes )
@@ -1659,7 +1658,7 @@ def clf(self, keep_observers=False):
1659
1658
self .images = []
1660
1659
self .legends = []
1661
1660
if not keep_observers :
1662
- self ._axobservers = []
1661
+ self ._axobservers = cbook . CallbackRegistry ()
1663
1662
self ._suptitle = None
1664
1663
if self .get_constrained_layout ():
1665
1664
layoutbox .nonetree (self ._layoutbox )
@@ -1917,10 +1916,9 @@ def gca(self, **kwargs):
1917
1916
return self .add_subplot (1 , 1 , 1 , ** kwargs )
1918
1917
1919
1918
def sca (self , a ):
1920
- """Set the current axes to be a and return a ."""
1919
+ """Set the current axes to be *a* and return *a* ."""
1921
1920
self ._axstack .bubble (a )
1922
- for func in self ._axobservers :
1923
- func (self )
1921
+ self ._axobservers .process ("_axes_change_event" , self )
1924
1922
return a
1925
1923
1926
1924
def _gci (self ):
@@ -1960,12 +1958,10 @@ def _gci(self):
1960
1958
def __getstate__ (self ):
1961
1959
state = super ().__getstate__ ()
1962
1960
1963
- # the axobservers cannot currently be pickled.
1964
- # Additionally, the canvas cannot currently be pickled, but this has
1965
- # the benefit of meaning that a figure can be detached from one canvas,
1966
- # and re-attached to another.
1967
- for attr_to_pop in ('_axobservers' , 'show' ,
1968
- 'canvas' , '_cachedRenderer' ):
1961
+ # The canvas cannot currently be pickled, but this has the benefit
1962
+ # of meaning that a figure can be detached from one canvas, and
1963
+ # re-attached to another.
1964
+ for attr_to_pop in ('show' , 'canvas' , '_cachedRenderer' ):
1969
1965
state .pop (attr_to_pop , None )
1970
1966
1971
1967
# add version information to the state
@@ -1998,7 +1994,6 @@ def __setstate__(self, state):
1998
1994
self .__dict__ = state
1999
1995
2000
1996
# re-initialise some of the unstored state information
2001
- self ._axobservers = []
2002
1997
FigureCanvasBase (self ) # Set self.canvas.
2003
1998
self ._layoutbox = None
2004
1999
@@ -2031,7 +2026,9 @@ def make_active(event):
2031
2026
2032
2027
def add_axobserver (self , func ):
2033
2028
"""Whenever the axes state change, ``func(self)`` will be called."""
2034
- self ._axobservers .append (func )
2029
+ # Connect a wrapper lambda and not func itself, to avoid it being
2030
+ # weakref-collected.
2031
+ self ._axobservers .connect ("_axes_change_event" , lambda arg : func (arg ))
2035
2032
2036
2033
def savefig (self , fname , * , transparent = None , ** kwargs ):
2037
2034
"""
0 commit comments