Maintaining thread safety can be cumbersome and difficult at times so in this recipe we will create three useful utilities that will make working with threads easier. We will create two decorator functions and a metaclass to help make applying thread safe rules to methods and functions as simple as adding a single line of code.
Here, will create a little utility module that can be used to help any wxPython application that needs to work with threads:
import wx import threading from types import FunctionType, MethodType __all__ = ['callafter', 'synchfunct', 'ClassSynchronizer']
Starting here, we will create a simple decorator function that can be used to decorate any method in a GUI class, so that if a call to the decorated method is made from a background thread, it will automatically delegate the call to the CallAfter
function:
def callafter(funct): """Decorator to automatically use CallAfter if a method is called from a different thread. """ ...