3

Is any way to continue executing try block if an exception is raised? I think that the aswer is no, but I think that the following code is ugly.

def preprocess(self, text):
    try:
        text = self.parser(text)
    except AttributeError:
        pass
    try:
        terms = [term for term in text if term not in self.stopwords]
        text = list_to_string(terms)
    except AttributeError:
        pass
    try:
        terms = [self.stemmer.stem(term) for term in text]
        text = list_to_string(terms)
    except AttributeError:
        pass
    return text

There is another way to do this in a pythonic form?

Marco Canora
  • 335
  • 2
  • 15

1 Answers1

2

I would rewrite it in this way:

def preprocess(self, text):
    if hasattr(self, 'parser'): 
        text = self.parser(text)

    if hasattr(self, 'stopwords'): 
        terms = [term for term in text if term not in self.stopwords]
        text = list_to_string(terms)

    if hasattr(self, 'stemmer'):        
        terms = [self.stemmer.stem(term) for term in text]
        text = list_to_string(terms)

    return text

I think it's much easier to understand and would not catch AttributeError inside parser and stem calls

alexey
  • 706
  • 5
  • 9