Search code examples
pythonprogramming-languages

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.)


Solution

  • 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.