Python: Throw Exception Or Return None?
Solution 1:
The latter matches what you would expect with standard Python types, and can be simplified to:
defget_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:
defget_Entity(self, id):
return self.my_dict.get(id)
).
Solution 2:
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
Solution 3:
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.
Post a Comment for "Python: Throw Exception Or Return None?"