Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Throw Exception or return None? [closed]

I want to get your feedback on which of the two snippets is the more pythonic way to handle a lookup.

I'm developing a wrapper for an XML File. I'm loading the XML file, parsing it, store the content in a dictionary and then allow the access through a class method.

Specifically - if the a given returns no result, should I return None or raise an (Key)Error?

I'm a bit confused, because some people suggested me to throw an Error instead of returning an empty value. They said it would be easier and clearer to handle then the error no a higher level.

This is a simplified version of the code:

class NoResult(KeyError):
    pass



class Wrapper(object): 
    ....

    self.my_dict = {}

    ....

    get_Entity(self, id):
        if id in self.my_dict:
            value = self.my_dict[id]
            return value
        else:
            return None





class Wrapper(object): 

    ....

    self.my_dict = {}

    ....

    get_Entity(self, id):
        if id in self.my_dict:
            value = self.my_dict[id]
            return value
        else:
            throw NoResult

I would really appreciate your thoughts!

like image 655
dh1tw Avatar asked Jan 11 '23 17:01

dh1tw


1 Answers

The latter matches what you would expect with standard Python types, and can be simplified to:

def get_Entity(self, id):
    return self.my_dict[id]

This will raise the KeyError for you if id isn't in self.my_dict. Getting an error tells the calling function that what was expected to be in the dictionary wasn't - quietly returning None leaves you open to subtle bugs later (unless you immediately check if val is None, in which case you could have used try anyway).

(The other version can also be simplified, to:

def get_Entity(self, id):
    return self.my_dict.get(id)

).

like image 65
jonrsharpe Avatar answered Jan 18 '23 23:01

jonrsharpe