(Originally published on prahladyeri.github.io)
There is an increasing trend towards using the dict.get() method in Python, its very widely used i...
For further actions, you may consider blocking this person and/or reporting abuse
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 -
It is nicer to write
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)
Letting Python raise an exception and catch it is also valid :)
Python embraces the concepts of EAFP (easier to ask forgiveness than permission) over LYBL (look before you leap):
EAFP
LYBL
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 👀
I think never in the title is too exaggeration