Coverage for ase/gui/observer.py: 76.67%

30 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1import gc 

2import warnings 

3import weakref 

4 

5 

6class Observers: 

7 def __init__(self): 

8 self.observer_weakrefs = [] 

9 

10 def register(self, observer): 

11 if hasattr(observer, '__self__'): # observer is an instance method 

12 # Since bound methods are shortlived we need to store the instance 

13 # it is bound to and use getattr() later: 

14 obj = observer.__self__ 

15 name = observer.__name__ 

16 else: 

17 obj = observer 

18 name = None 

19 self.observer_weakrefs.append((weakref.ref(obj), name)) 

20 

21 def notify(self): 

22 # Methods of windows that were closed already can be left behind, which 

23 # will lead to _tkinter.TclErrors, if they are registered here, because 

24 # they try to call Tk functions on windows that don't exist anymore 

25 # (issue ase/ase#1909) 

26 # The easy fix is to run garbage collection before sending out notices: 

27 gc.collect() 

28 # We should probably add an event class to these callbacks. 

29 weakrefs_still_alive = [] 

30 for weak_ref, name in self.observer_weakrefs: 

31 observer = weak_ref() 

32 if observer is not None: 

33 weakrefs_still_alive.append((weak_ref, name)) 

34 if name is not None: 

35 # If the observer is an instance method we stored 

36 # self, for garbage collection reasons, and now need to 

37 # get the actual method: 

38 observer = getattr(observer, name) 

39 

40 try: 

41 observer() 

42 except Exception as ex: 

43 import traceback 

44 

45 tb = ''.join(traceback.format_exception(ex)) 

46 warnings.warn( 

47 f'Suppressed exception in observer {observer}: {tb}' 

48 ) 

49 continue 

50 

51 self.observer_weakrefs = weakrefs_still_alive