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.)
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.
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
andexcept
statements. The technique contrasts with the LBYL style common to many other languages such as C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With