Beware of Python dict.get()

Pierre on March 11, 2019

If you think that value = my_dict.get('my_key', 'default_value') is equivalent to value = my_dict.get('my_key') or 'default_value' you should pr... [Read Full]
markdown guide

Wouldn’t or also fail if the value was something like 0 or False?

In [1]: 0 or {}
Out[1]: {}

In [2]: False or {}
Out[2]: {}

This adds a strong technique to my repertoire and also some "gotchas" to look out for. Thank you!


That's pretty horrifying.
What's the robust solution here? Using a validation lib that will verify the whole data against a schema, and then have type annotations for the validated object?


Checking the return value properly. Or, just going for it and catching exceptions:

    price_from_extruct = data_from_extruct['offer']['amount']
    price_from_extruct = 0  # If you really wanted to do this.

The thing is, I find exceptions a good way of handling complex and arbitrary error flows. If you don't have a good story for what to do, trying to avoid the exceptions is just causing more headaches later.

code of conduct - report abuse