1

i am wondering whether this is possible to do in Python 3.x

i have a function in a class that is quite long (time wise), it takes a few minutes to finish running. I am wondering whether I can force it to stop with an exception. But I want to have control of that exception so that I can trigger it any time.

A trivial solution, would be to check for my order x, if it is true I raise an exception and put this code at key points in the function. However this is tedious for long functions. But I am wondering whether there is a more efficient way to do it. something like wrapping the function with some custom library that can do this (periodically checks for x, and throws an exception to force the function to stop)

def function():
   ...
   if x:
      raise Exception
   ...
   if x:
      raise Exception
   ...
   if x:
      raise Exception
   ...

Thank you

Josh.h
  • 71
  • 1
  • 13
  • Real question is, how would you set that `x` if you are currently running `function()`? Multithreading? Async? – matszwecja Feb 01 '22 at 14:55
  • x could be an attribute of the class of which function() is part of – Josh.h Feb 01 '22 at 14:57
  • And what will trigger the change in `x`? If it happens within `function()` then you should be able to catch in in the specific place it may happen. – matszwecja Feb 01 '22 at 14:59
  • x can be changed externally. it is a user command. this question is part of a bigger code... – Josh.h Feb 01 '22 at 15:01
  • Then getting that bigger code might prove useful for answering your question. If it is a variable then there must be some event that causes the change. – matszwecja Feb 01 '22 at 15:07
  • the multiprocessing presented as a solution to this solution answers my question. thank you – Josh.h Feb 01 '22 at 15:14

0 Answers0