chay.dev

A random gotcha in Python

Back to basics

devpythonbasics

Let’s say you want to get the value of a key in a dictionary

example_dict = {
    “key_one”: “value_one”
}

The built-in accessor syntax is dict[key]

output = example_dict[“key_one”]
print(output)
# “value_one”

What if you have no way to find out if a key exist? If a key does not exist and you try to access it using the square brackets, you will get an error

output = example_dict[“some_key”]
# KeyError

The “safe” approach is to use the .get method on the dictionary object

output = example_dict.get(“some_key”)
print(output)
# None

Don’t use this all the time though; sometimes, you need to fail fast in order to catch problems in your code.

Okay, what if you want to execute a function if the key does not exist?

def return_two():
    print(“function invoked”)
    return “value_two”

output = example_dict.get(“key_two”, return_two())

Spoiler: “function invoked” gets printed. Under the hood, the return_two function is called first, and then result is passed in to the .get function.

In cases like this, you should always be aware of whether you want to invoke the function, if the key exists in the dictionary. Don’t be surprised if the key exists in the dictionary and the function is called anyway!

To avoid this, you can do either

# method 1
output = example_dict[“key_two”] if “key_two” in example_dict else return_two()

# method 2: I prefer this
output = example_dict.get(“key_two”)
if output is None:
    output = return_two()

Neither are elegant solutions.