I’m writing a wxPython application that will be doing quite a bit of data analysis and display. The way I’ve written it so far has led to problems when two threads try to change
For posterity, here is the decorator I created using Yoriz’s answer.
def run_on_main_thread(fn):
"""Decorator. Forces the function to run on the main thread.
Any calls to a function that is wrapped in this decorator will
return immediately; the return value of such a function is not
available.
"""
@wraps(fn)
def deferred_caller(*args, **kwargs):
# If the application has been quit then trying to use
# CallAfter will trigger an assertion error via the line
# assert app is not None, 'No wx.App created yet'
# Since assertions are optimized out when -O is used,
# though, it seems safest to perform the check ourselves,
# and also catch the exception just in case.
if wx.GetApp() is not None:
try:
wx.CallAfter(fn, *args, **kwargs)
except AssertionError:
pass
return deferred_caller