I want to pass caught instance of an Exception
(or deriving class) as and argument to some function, and I wonder if it is an idiomatic (pythonic) thing to do. In summary I have a system that runs different callbacks depending on success of some other method call. In reduced form it looks like this:
class Foo:
def bar(self):
pass
def callback_success(self):
pass
def callback_error(self):
pass
and it is used in some other part of my code like this:
foo = Foo()
was_success = True
try:
foo.bar()
except Exception:
was_success = False
foo.callback_error()
if was_success:
foo.callback_success()
Now I would like to pass to callback callback_error
more information about what exactly went wrong. I come up with an idea of passing caught exception as an argument of callback_error
. So doing something like this:
def callback_error(self, ex: Exception):
pass
except Exception as e:
foo.callback_error(e)
I can see that this solution will work, but I wonder if it is a good idea to pass caught exceptions as values. So my question is, is this considered pythonic or not? The only thing that I can see wrong with this is that it feels a little bit odd. I never have seen such "pattern" used by anybody else before. Are there some other thing that I should know about, that make this a bad code? What would you thing when you would encounter code like this in your code base?