0

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?

Aleksander Krauze
  • 3,115
  • 7
  • 18
  • Uh, why wouldn't it be? Instances of `Exception` and its subclasses are just ordinary instances. If you want to process an instance of something in a repeatable way you would encapsulate that process in a function that would accept the instance of interest - in your case, the exception instance would be the thing to pass, right? – metatoaster May 30 '23 at 06:26
  • Practical examples of where they might occur [here](https://stackoverflow.com/questions/18101887/can-i-pass-an-exception-as-an-argument-to-a-function-in-python), [here](https://stackoverflow.com/questions/41046353/how-to-pass-exception-from-one-process-to-another), [here](https://stackoverflow.com/questions/41170269/checking-if-an-object-is-an-exception-class) and properly more. – metatoaster May 30 '23 at 06:30
  • @metatoaster That makes sense. This was pretty much my internal argument. I guess I wanted assurance that indeed I did not missed anything. Thanks for provided links. – Aleksander Krauze May 30 '23 at 06:36

0 Answers0