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?
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
try
section ? - ᴀʀᴍᴀɴtry
has stopped and thus where to continue. The only solution would be to surround every statement with atry
... - Willem Van Onsemfrom contextlib import suppress with suppress(AttributeError):
- Jean-François Fabre