Avoiding Pitfalls With EAFP
00:00 What To Avoid When Using EAFP. EAFP, as I’m sure you know by now, is a powerful tool, but with great power comes great responsibility. So here’s a couple warnings that you’ll want to pay close attention to.
00:12 The first is to avoid using bare exceptions. The second is to avoid causing side effects. We’ll go over these in detail over the next few slides and a little live coding.
00:23
So what is a bare exception? A bare exception occurs when you use try ... except
without specifying an Exception
class. When different kinds of errors are possible, you probably want to handle them differently.
00:35
So it’s very important to use specific error classes for your except
clauses.
00:42
On the left you can see a simple bare exception. try
do_something()
, except
pass
. On the right, you can see the preferred style.
00:51
try
do_something()
, except
ValueError
, have some specific code for handling the ValueError
or except
an IndexError
, have some specific code there to handle the IndexError
, and you can continue this for as many error classes as you like.
01:07 In this way, you can be certain that your code will handle the errors specifically based on the type of error that was raised.
01:15 What about side effects? A side effect occurs when a function interacts with code outside of its scope. Some important side effects to watch out for are network requests, database operations, and file system interactions.
01:29 Let’s look at the specific example of writing to a file.
01:33
Here we have a Python program that writes a greeting to a file called hello.txt
and the greeting that it writes is going to be based on one of these values in the list of moments we have defined at the top.
01:46
Let’s go through it line by line. First we have the list of moments
, moments of time, three string values, ‘morning’, ‘afternoon’, and ‘evening’.
01:55
Next, we have the index that will be used to determine which greeting is going to be written to the file. Currently, index holds the integer value of 3
.
02:05
Then, we open the file called hello.txt
, and the mode that it’s opened in is write mode, which is what the w
is for, and the encoding is utf-8
, the most common text encoding. This file will be stored in the variable hello
, and that’s how we’ll access it in the rest of this with
block.
02:24
Next, because this is EAFP, we’re using try ... except
to safely write to this file. First, we call hello.write
‘Good’, that will produce a new line.
02:36
Next, hello.write
moments
at whatever the value of index is and that will be inserted using a Python f-string. In the case of an IndexError
, which would happen if the index that we try to access is invalid, the program will print ‘An error occurred’.
02:52 So let’s see what happens when we run this file. Use the integrated terminal.
02:59
As you probably expected, an error occurred. Why is that? Because we set the index to 3
. Because Python lists are zero-indexed, that means the index of the last item in this list would actually be index 2
, and 3
creates an IndexError
.
03:15
But something else that happened is hello.txt
was still written to, as you can see, we have ‘Good’ written to the file. And that’s because we wrote that to the file before the code that triggered the error.
03:29
And that is a side effect. To prevent this kind of side effect, your try
block should only consist of code that can potentially raise an error.
03:37
So to fix it, remove the current code and assign the moment
to a variable inside the try
block.
03:46
Now you can add a new section to your try ... accept
, else
. Code in the else
block will only run if no error is encountered.
03:53
This is the perfect place to put the actual file writing code. The else
block goes right after the except
block and should be on the same indentation level as the try
and except
keywords. Within the else
, first call hello.write
, and pass in the string ‘Good\n’ for a new line.
04:12
On the next line, call hello.write
and pass in moment
. This way, the moment that was accessed in the try
block can be written to the file and the file will only be written to if the try
block succeeds.
04:25
You can also delete the old hello.txt
because this will be created again.
04:35 Save the file and run the new code.
04:41
Once again, an error occurred. Let’s take a look at hello.txt
. It’s empty. Perfect. We didn’t write something we didn’t want to write. For good measure, you can change index to zero,
04:55 save the file, and run the code again to see if it works as intended.
05:00
No error message. That’s a good sign. Let’s take a look at hello.txt
05:05
and Good morning
is what’s printed. This may seem tricky right now, but with practice avoiding side effects like this will soon become second nature. By moving the side effect causing code out of the try
block, leaving only potentially error-causing code, you avoided writing to a file unintentionally.
05:24 You can use similar techniques when dealing with other code that has side effects such as network requests, database operations, or other kinds of file system interactions.
05:34
Placing such code in the else
block will prevent inadvertent side effects and overall make your code much safer.
Become a Member to join the conversation.