DEV Community

loading...

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

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 👀