Loading video player…

Looking Before You Leap

00:00 So at this point, you’re probably wondering what exactly is LBYL or Look Before You Leap? Just as it sounds, you are looking ahead, trying to predict where an error might occur in your code and then taking specific actions to avoid that happening.

00:16 If you’re like me, constantly imagining worst-case scenarios, then this probably comes pretty naturally to you. This is also the classic approach because earlier on in programming, error catching using something like Python’s try and except wasn’t even an option, and this was the way to make sure that your code ran safely.

00:35 This is typically applied using conditional logic such as an if-else block in Python to avoid the errors. It also requires that you’re able to correctly identify the inputs that may lead to errors down the road.

00:50 Now let’s look at an example with Python code.

00:54 So you’ll be working in the Python REPL for this.

00:58 It takes only a few lines of code to see how the LBYL style can be useful for a very common situation: accessing a missing key in a dictionary. As you probably know, if you try to access a key in a dictionary that doesn’t exist in that dictionary, Python will raise a KeyError.

01:15 So to avoid that, first you’ll want to create a dictionary. You can use any name you want here. I’m going to use Joseph because I’m biased towards that name.

01:26 Now that you’ve got your dictionary, just imagine that you got up, went for a walk, went to see a movie, came back, and decided to continue writing your code.

01:35 How was the movie? I hope it was good. Anyway, maybe you’ve forgotten exactly what was defined in the dictionary that you wrote ages ago, and you kind of remember there being an email key and you want to store that in a variable.

01:52 Oops, I guess you were too busy being swept away by the silver screen and now we have a KeyError because, of course, ‘email’ is not contained in the dictionary.

02:02 So how can you use LBYL to look before leaping, in this case? You’ve got it. You’re going to use an if-else block.

02:27 So what’s happening in this code? First, if will check the condition, whether the string email is one of the keys in the data_dict.

02:37 If that check returns false, we will skip on to the else where the print() function is going to output a message, letting the user know, Hey, that key wasn’t there, but we avoided the error. First, you looked at the dictionary to see if the email key existed before leaping by trying to access it.

02:56 And that’s LBYL. Let’s see if this works.

03:01 And there you go. Key not found, error avoided. And just like that, you used conditional logic in just a few extra lines of code to avoid a potentially application-breaking error.

03:13 Well done! Next up, you’ll dive into the alternative style EAFP.

Become a Member to join the conversation.