I have the following scenario: Program A uses library L. Library L defines some exceptions. If an exception defined in L is raised in A, I want to serialize it into a json and send it via some channel (e.g. redis). This exception is then received by some program B where I want to deserialize the exception and do something with it. In order to be able to deserialize the exception, B needs to know all the exceptions defined in L. How would I get all exceptions from L? Would it make sen to loop through all members of L and check if they are subclasses of Exception?
Asked
Active
Viewed 43 times
1
-
`import` operates on names, I don't think there's any way to filter imports by data type. – Barmar Jun 23 '23 at 23:52
-
Perhaps all of L's exceptions are subclasses of a common base class. You could import that base class and use it in your `except` statements. – Barmar Jun 23 '23 at 23:53
-
Not an answer, but as an alternative, if you add all the necessary information to the json, you should be able to dynamically deserialize any exception in [this way](https://stackoverflow.com/questions/4821104/dynamic-instantiation-from-string-name-of-a-class-in-dynamically-imported-module). – ken Jun 24 '23 at 09:45
1 Answers
0
In order to de-serialize the exceptions in B
, L
must be importable from B
, with the same full name that it is importable in A
.
If both A
, B
and L
are part of the same Python package, it would just work. If A
and B
are in different packages, you'd better refactor L
to live in its own stand-alone package (not depending from A
), and make it a dependency of B
.

jsbueno
- 99,910
- 10
- 151
- 209