Reputation: 193
I am using a package which provides a class whose methods make an external call and throws an exception if conditions are not met. This is widely consumed in code I do not own and cannot modify. I would like to somehow capture the exception, perform an action, and retry the original call. The code I do own however is instantiating the class as a singleton to be shared by the rest of the code.
The package (uneditable)
class A:
def doaction():
try:
action() # external service call which raises exception if conditions are not met
except:
raise Exception
def doaction_a():
return doaction()
def doaction_b():
return doaction()
...
Consumer (uneditable)
class consumer():
def failing():
client.doaction()
My code (where the fix will be, hopefully)
def setup_connection():
auth = generate_key()
client = A(auth) # client is now available for consumer to access
Apologies if this is something absurd, I am open to suggestions. The goal is to capture the exception, fix the conditions which made it so, and retry the action without modifying the package nor the consumer codebase.
Upvotes: 0
Views: 360
Reputation: 83537
One solution is to extend the class:
class B(A):
def do_action():
try:
super().do_action()
except Exception:
# log it or whatever
Now just create an instance of B
as your singleton.
Upvotes: 0
Reputation: 781096
Define a child class that overrides the method and catches the exception.
define myA(A):
def doaction(self, *args, **kwargs):
while True:
try:
super().doaction(self, *args, **kwargs)
break
except Exception:
# fix conditions
Then instantiate this class in your code instead of A
.
Upvotes: 2