Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some languages return nil when a key is not in a dictionary, while Python throws an exception?

I am interested in learning the rationale behind the following behaviour:

In Ruby,

irb(main):003:0> dic = {:a => 1, :b => 2}
=> {:a=>1, :b=>2}
irb(main):004:0> dic[:c]
=> nil

In Javascript:

> var dic = {a: 1, b: 2};
undefined
> dic['c']
undefined

Clojure:

user=> (def dic {:a 1 :b 2})
#'user/dic
user=> (:c dic)
nil

While in Python:

>>> dic = {'a': 1, 'b': 2}
>>> dic['c']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'

I would like to know why Python's (default) behaviour is to raise an exception instead of returning some form of nil like the other languages listed above. I didn't see the answer in the design faq. (I guess an equivalent question would be asking why the other languages do what they do, but Python seems to be the oddball in this respect.)

like image 287
DJG Avatar asked Sep 13 '13 18:09

DJG


2 Answers

From the Zen of Python (import this):

 Errors should never pass silently.
 Unless explicitly silenced.

Meaning, a key not found is treated as an error, unless you explicitly code for it, e.g. by catching KeyError or using the dict.get(key, default) method.

Python was explicitly designed to be very explicit in this and (most) other respects.

like image 74
Thomas Avatar answered Sep 26 '22 11:09

Thomas


EAFP(Easier to ask for forgiveness than permission):

This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

like image 32
Ashwini Chaudhary Avatar answered Sep 22 '22 11:09

Ashwini Chaudhary