Not too sure if I am following best practices. In my class I have a __call__
that runs multiple class functions when called. In one of the functions, if an exception is met, I want to break out of the call such that the other functions do not run.
def __call__(self,event):
self.f1(event)
self.f2()
self.f3()
self.f4()
self.f5()
self.f6()
in one of the functions I have some logic
def f2(self):
try:
somelogic
except otherlogic as error:
doSomeOtherStuff
when an exception is caught in f2, I do not want to continue the call to f3,f4, etc.
If I am not using object calls correctly I am open to alternatives
I think the easiest way is to re-raise the exception in f2, ie
def f2(self):
try:
somelogic
except otherlogic as error:
doSomeOtherStuff
raise
You may then want to handle this _ call _ ie
def __call__(self,event):
try
self.f1(event)
self.f2()
self.f3()
self.f4()
self.f5()
self.f6()
except:
do_something
There's a couple of options.
For the first option, you'd wrap the entire call list in a try/except block like this:
try:
self.f1(event)
self.f2
...
except MyCustomException:
pass
For the second option you'd call them like:
if not self.f1(event):
return
if not self.f2():
return
...
I think an easier route is storing all your functions in a list and then running through a for loop. If you run into an exception, you break from the for loop.
I would also recommend not messing around with the dunder method __call__
unless you have a good reason. Calling 6 functions when calling an object is not necessarily intuitive and may lead to other developers not understanding what's happening when working with your code. As an alternative, call a function directly instead. In my example here, I am calling it start_process .
from typing import Callable, List
def start_process() -> None:
list_of_functions: List[Callable] = [f1, f2, f3, f4, f5, f6]
for fn in list_of_functions:
try:
fn()
except Exception:
break
# do other logic
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.