Dev
Dev

Reputation: 13753

Retry in python methods

This is the standard language-neutral approach

import logging

logger = logging.getLogger(__file__)

class SomeClass(object):
    max_retry = 2

    def get(self, key):
        try:
            return self.__get_value(key)
        except Exception:
            logger.error("Exception occured even after retrying...")
            raise

    def __get_value(self, key, retry_num=0):
        try:
            return self.connection().get(key)
        except Exception:
            logger.error("Exception occured")
            if retry_num < self.max_retry:
                retry_num += 1
                logger.warning("Retrying!!! Retry count - %s", retry_num)
                self.__get_value(key, retry_num)
            else:
                raise

Is there any better pythonic way to do this?

Upvotes: 0

Views: 71

Answers (1)

Martin Vo
Martin Vo

Reputation: 11

Cleaner approach would be not to change state of the class since it's retry just for the function call (current implementation wouldn't work as expected when the method is called multiple times). I'd prefer a retry decorator (as loop with break when succeed) used as:

...
@retry(n_times=2, catch=Exception)
def get (self, key):
    ...

Upvotes: 1

Related Questions