Rob Cook


Home | GitHub | Dev.to | Donate | Contact

Look before you leap


2025-01-20

Coming from C# it's considered good practice to look before you leap with your code. For example, assume you are accessing a value in a dictionary by key. You would first check to make sure the key is present in the dictionary, before forging ahead with the call to access it.


var dict = new Dictionary();
var key = "my_key";
object? value = null;

if (dict.ContainsKey(key))
{
    value = dict[key];
}
else
{
    // Do something about the missing key.
}

This caution allows us to avoid the expense of an exception should the key not be found. However it comes at the cost of checking for the key twice - once for existence, and once for accessing the value. In Python this is considered a bad thing. The advice there is "easier to ask forgiveness than permission". Idiomatic Python code would therefore take the other route and risk the exception when the key is missing.


d = {}
key = "my_key"
try:
    value = d[key]
except KeyError as e:
    # Do something about the missing key

The reasoning is that the happy path (in this case the one where the key exists) should be as speedy as possible. Avoiding the double lookup on the key is therefore considered a good thing.

Its little philosophical things like this that mark out a native Python coder, from one coming at it from another language. Learning to embrace the culture of a programming language is just as important as learning the syntax and standard libraries.

end