geekpradd / PyDictionary

PyDictionary is a Dictionary Module for Python 2/3 to get meanings, translations, synonyms and antonyms of words
https://pypi.python.org/pypi/PyDictionary
MIT License
274 stars 65 forks source link

Add ability to let user implement functionality if word is not found(Question about implementation) #27

Closed BridgetNichols closed 5 years ago

BridgetNichols commented 5 years ago

I'm currently implementing a feature where if a word is not found when meaning() synonym() or translate() is called it will either return None or raise an exception. This way, the user can add functionality if the word is not found.

Example of raising an exception:

@staticmethod
    def synonym(term, formatted=False):
        if len(term.split()) > 1:
            print("Error: A Term must be only a single word")
        else:
            try:
                data = _get_soup_object("https://www.thesaurus.com/browse/{0}".format(term))
                section = data.find('section', {'class': 'synonyms-container'})
                spans = section.findAll('span')
                synonyms = [span.text for span in spans[:5]]
                if formatted:
                    return {term: synonyms}
                return synonyms
            except:
                print("{0} has no Synonyms in the API".format(term))
                raise InvalidTermError("{0} has no synonym in the API".format(term)) # InvalidTermError would be defined in an additional file exceptions.py

Example of returning None:

@staticmethod
    def synonym(term, formatted=False):
        if len(term.split()) > 1:
            print("Error: A Term must be only a single word")
        else:
            try:
                data = _get_soup_object("https://www.thesaurus.com/browse/{0}".format(term))
                section = data.find('section', {'class': 'synonyms-container'})
                spans = section.findAll('span')
                synonyms = [span.text for span in spans[:5]]
                if formatted:
                    return {term: synonyms}
                return synonyms
            except:
                print("{0} has no Synonyms in the API".format(term))
                return None

I don't know which way would be better. Any feedback would be appreciated and I'll implement this based on feedback.