DEV Community

Cover image for Why you should never use the dict.get() method in Python

Why you should never use the dict.get() method in Python

Prahlad Yeri on November 28, 2019

(Originally published on prahladyeri.github.io) There is an increasing trend towards using the dict.get() method in Python, its very widely used i...
Collapse
 
kfirstri profile image
Kfir Stri • Edited

Cool post Prahlad! I think 'never' is a bit harsh, I agree that checking if the key exists before or if you know the key will be in the dict you should access it directly.. but, the get method is useful sometimes for default values, not just to return None..

If you got some dict full with booleans for some reason, instead of writing -

if 'some_bool' in bool_dict:
   result = bool_dict['some_bool']
else:
   result = False

It is nicer to write

result = bool_dict.get('some_bool', False)

Or many other use cases where you can use the default argument to make the .get method return something other than None (maybe your program has some default config parameters, or maybe you want to set a different string.. and so on)

Collapse
 
rhymes profile image
rhymes

Letting Python raise an exception and catch it is also valid :)

try:
  x = d['a']
except KeyError:
  # do something else

Python embraces the concepts of EAFP (easier to ask forgiveness than permission) over LYBL (look before you leap):

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.

LYBL

Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.

EAFP is also safer in multithreaded environments (though you probably wouldn't directly access a plain dictionary anyway, but that's another story).

Exceptions in Python are quite cheap, even though sometimes are used as a control statement like this 👀

Collapse
 
cpt9m0 profile image
Ali Ayati

I think never in the title is too exaggeration