3

This question already has an answer here:

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?


  • You can use the finally keyword errors in python - omri_saadon
  • Yes, but if do that there is a lot of nested code - Marco Canora
  • Why all statement are not in one try section ? - ᴀʀᴍᴀɴ
  • @omri_saadon: yeah but the problem with that is that you do not know where the try has stopped and thus where to continue. The only solution would be to surround every statement with a try... - Willem Van Onsem
  • maybe with contextlib: from contextlib import suppress with suppress(AttributeError): - Jean-François Fabre

1 답변


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


  • yes, it's better to avoid exceptions if possible. +1 for thinking outside the box of this duplicate question. - Jean-François Fabre

Linked


Related

Latest