Sean Grant
Sean Grant

Reputation: 193

How do I extend a class method to surround it in a try..catch without changing implementation in consuming code?

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

Answers (2)

Code-Apprentice
Code-Apprentice

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

Barmar
Barmar

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

Related Questions