Question

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!

Was it helpful?

Solution

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)

).

OTHER TIPS

dict already contains the 2 behaviors. (get -> None and [] -> KeyError).

Also, None is a valid value for a dict:

my_dict = {'key': None}
my_dict['key']
# Returns None

Ok, this will be a little bit generic but looks at the expectations of the programmer using your library. If I am doing a lookup in an XML file I am probably expecting that I will get a result.

Lets say I am then a lazy programmer who does no validation of what you return to me and try and use it. If you return to me a special none value my code will continue to run and will encounter an error later and it may not be obvious to me that that is the root cause.

On the other hand if you threw an exception as soon as I requested the invalid value my program would crash immediately and give me an accurate explanation of what went wrong.

If programmers all did careful validation on what your library returns either way will work fine but lazier (read most :P) programmers will likely not do so, thus the exception route will provide the least surprise and confusion. As a library you never want to surprise or confuse your user when avoidable so I would go for the exception route.

However I shall quickly note, if doing an invalid lookup is a 'normal' action in your libraries work-flow you can more reasonably expect programmers to check so then either becomes reasonable.

Remember the rule of thumb, use an exception when the action is actually exceptional and surprising, otherwise ymmv but you probably dont have to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top