@@ -1617,8 +1617,7 @@ def _break_share_link(ax, grouper):
1617
1617
return None
1618
1618
1619
1619
self ._axstack .remove (ax )
1620
- for func in self ._axobservers :
1621
- func (self )
1620
+ self ._axobservers .process ("_axes_change_event" , self )
1622
1621
self .stale = True
1623
1622
1624
1623
last_ax = _break_share_link (ax , ax ._shared_y_axes )
@@ -1654,7 +1653,7 @@ def clf(self, keep_observers=False):
1654
1653
self .images = []
1655
1654
self .legends = []
1656
1655
if not keep_observers :
1657
- self ._axobservers = []
1656
+ self ._axobservers = cbook . CallbackRegistry ()
1658
1657
self ._suptitle = None
1659
1658
if self .get_constrained_layout ():
1660
1659
layoutbox .nonetree (self ._layoutbox )
@@ -1910,10 +1909,9 @@ def gca(self, **kwargs):
1910
1909
return self .add_subplot (1 , 1 , 1 , ** kwargs )
1911
1910
1912
1911
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* ."""
1914
1913
self ._axstack .bubble (a )
1915
- for func in self ._axobservers :
1916
- func (self )
1914
+ self ._axobservers .process ("_axes_change_event" , self )
1917
1915
return a
1918
1916
1919
1917
def _gci (self ):
@@ -1953,12 +1951,10 @@ def _gci(self):
1953
1951
def __getstate__ (self ):
1954
1952
state = super ().__getstate__ ()
1955
1953
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' ):
1962
1958
state .pop (attr_to_pop , None )
1963
1959
1964
1960
# add version information to the state
@@ -1991,7 +1987,6 @@ def __setstate__(self, state):
1991
1987
self .__dict__ = state
1992
1988
1993
1989
# re-initialise some of the unstored state information
1994
- self ._axobservers = []
1995
1990
FigureCanvasBase (self ) # Set self.canvas.
1996
1991
self ._layoutbox = None
1997
1992
@@ -2024,7 +2019,9 @@ def make_active(event):
2024
2019
2025
2020
def add_axobserver (self , func ):
2026
2021
"""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 ))
2028
2025
2029
2026
def savefig (self , fname , * , transparent = None , ** kwargs ):
2030
2027
"""
0 commit comments