Search code examples
pythonexceptionprofilesys

sys profile function becomes none after exception is raised


I am currently using a custom profile function that I set with sys.setprofile. The goal of the function is to raise an exception if we are in the main thread and if a timeout thread gave the signal to do so and we are within a specific scope of the project that properly handles specific exceptions.

def kill(frame, event, arg):
   whitelist = [
       r'filepath\fileA.py',
       r'filepath\fileB.py'
   ]

   if event == 'call' and frame.f_code.co_filename in whitelist and kill_signal and threading.current_thread() is threading.main_thread():
      raise BackgroundTimeoutError
   return kill

It works perfectly, however, as soon as the exception is raised the profile function becomes unset. So after raising an exception inside a try/except block and calling sys.getProfile() it returns None.

sys.setprofile(kill)
print(sys.getProfile()) <----- this returns the profile function
try:
   function_that_raises_backgroundtimeouterror()
except:
   pass
print(sys.getProfile()) <----- this returns None

Why is the profile function being unset and how can I overcome this? Is there a way to permanently set the function or reset it when unset?


Solution

  • Profile functions are meant for profiling, not for raising exceptions. If a profile function raises an exception, Python assumes it's broken and unsets it.

    The documentation says:

    Error in the profile function will cause itself unset.