DEV Community

loading...

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

Collapse
hanpari profile image
Pavel Morava

Oh, not so fast. I have several reasons to disagree.
First of all, you omitted to write full signature of the method.


dict.get(self, key, default=None)

You see, there is a default parameter which doesn't need to be None. It can be whatever you find relevant, even KeyError if you insist.

{"a":1}.get("b", KeyError("This key is not in this dictionairy."))
KeyError('This key is not in this dictionairy.')

But not only that, you should understand None is not like null in Java. None is a different type in Python.
What do I mean? Let's use typing module to make everything clear.

from typing import Dict, Optional

users: Dict[str, str]
users = {
    "user1": "address1",
    "user2": "address2"
}

user: Optional[str] = users.get("user3")

Clearly, there should be no confusion between type str and None. None indicates value which is missing. I think it is perfectly fine to use get method. In the case, you need to distinguish between not-existent key and None value in dictionairy, you have free options.

users.get("user?", "What user?")
'What user?'
users["user?"] if "user?" in users else "What user?"
'What user?'
try:
    users["user?"]
except KeyError:
    "What user?"

I saw try-except variant being recommended in concurrent environment as thread-safe. But honestly, I see no problem with get method whatsoever.