Python: throw an exception or return None?

I want to get your feedback on which of the two snippets is the more pythonic way of handling the search.

I am developing a wrapper for an XML file. I download the XML file, parse it, save the contents in a dictionary, and then allow access through the class method.

In particular, if the given value does not return a result, should I return None or raise a (Key) error?

I'm a little confused because some people suggested I throw an error instead of returning an empty value. They said that it would be easier and more understandable to handle the error then, and not 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 be very grateful for your thoughts!

+4
3

, Python, :

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

KeyError , id self.my_dict. , , , - None ( if val is None, try ).

( , :

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

).

+4

dict 2 . (getNone []KeyError).

, None dict:

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

, , , . XML, , , , .

, , , , . , , , .

, , , , .

, , , ( : P) , , , . , , .

, - "" , , .

, , , ymmv, , , .

+1
source

Source: https://habr.com/ru/post/1538094/


All Articles