Friday, December 30, 2022

Dict's get has a Default Value

 I found this pattern in several places in our Python code base:

state = "on"
if "State" in data and data["State"] == "off":
    state = "off"

The state here can have two values: on or off. So all this code can be pretty much replaced with this one line:

state = data.get("State", "on")

If the state is missing, it will get the value "on". Of course, you might say that it is not completely equivalent, since anything but "off" would be transformed into "on" in the first code. But then, this code is usually followed by this condition:

if state != "off":

I would have rather replaced the state variable with a boolean, and have a code like this one instead:

state_on = data.get("State") != "off"
if state_on:

If the state is missing, the get would return None, which is also different from "off".