Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Choosing Which Style to Use

00:00 At this point, you’ve had an in-depth look at both the Look Before You Leap and Easier to Ask Forgiveness Than Permission styles for dealing with errors. I know I promised you some situational guidelines on when you should apply each style.

00:12 This lesson is all about how to decide which approach is better for a given situation. So first, how likely is an exception to be raised? Will using EAFP make your code cleaner or easier to read?

00:26 Is your code at risk of a race condition and are there any potential side effects to your code? And what are they? When working on a team, you’ll always want to follow your team’s specific style guidelines.

00:39 Your team may decide upon a preference for defaulting to EAFP or LBYL, and in that case, as long as it makes sense, that should be your default style.

00:50 Here we have some general guidelines. For operations that are likely to fail and could be prevented consistently with a conditional check, use LBYL. If the operations are unlikely to fail, and where conditional checks wouldn’t validate the data well, you can use EAFP.

01:06 Think back to the example of converting a string to an integer.

01:11 In the case of irrevocable operations, or operations with side effects, Look Before You Leap can prevent you from doing something that can’t be undone. For our writing to a file example, LBYL would’ve been a great way to avoid side effects.

01:25 However, if the code is susceptible to a race condition, like in the case of input/output or network operations, EAFP is the way to go.

01:35 More generally, use LBYL for common exceptional conditions that are quick to prevent. And just like the database example we saw, EAFP is great for things like database connections that can be rolled back quickly.

01:48 Cases where if an error is raised, forgiveness can easily be granted.

01:53 With this, you now have a great roadmap for selecting between these two styles. Next up, we’ll review everything you’ve learned in the course and point you towards some additional resources.

Become a Member to join the conversation.