{ Debugging Python. }

Objectives:

By the end of this chapter, you should be able to:

  • Identify common errors in Python
  • Understand the causes of common errors in Python
  • Catch errors using try and except
  • set break points in your Python code

Just like in any programming language we learn, bugs are going to happen! As you've probably noticed, in Python we have quite a few errors. Let's review some of the common ones:

NameError

This occurs when a variable is not defined:

test
# NameError: name 'test' is not defined

KeyError

This occurs when a dictionary does not have a specific key:

d = {}
d["foo"]
# KeyError: 'foo'

AttributeError

This occurs when a variable does not have an attribute:

"awesome".foo
# AttributeError: 'str' object has no attribute 'foo'

IndexError

This occurs when you try to access an element in a list using an invalid index (i.e. one that is outside the range of the list):

list = ["hello"]
list[2]
# IndexError: list index out of range

ValueError

This occurs when a built-in operation or function receives an argument that has the right type but an inappropriate value:

int("foo")
# ValueError: invalid literal for int() with base 10: 'foo'

TypeError

This occurs when Python can not interpret two data types:

"awesome" + [] # TypeError: cannot concatenate 'str' and 'list' objects

raise

In python we can also throw errors using the raise keyword. This is helpful when creating your own kinds of exception and error messages.

raise ValueError('invalid value')

try / except

In Python, it is strongly encouraged to use try/except blocks, to catch exceptions when we can do something about them. Let's see what that looks like.

try: 
    foobar
except NameError as err:
    print(err)

We could also write something like this, but you should try not to. Why do you think someone might object to the following code?

try: 
    nice + []
except:
    print("Something went wrong!")

What we are doing here is catching every error, which means we are not able to correctly identify "what" went wrong. It is highly discouraged to do this. When you use try/except, make sure that a specific type of exception is being handled. If you want to except a handful of exceptions, you can pass a tuple of errors into the except block as well:

try:
    # do some stuff
except (NameError, ValueError) as e:
    # do some other stuff

Debugging with pdb

To set breakpoints in our code we can use pdb by inserting this line:

import pdb; pdb.set_trace() 

Inside of the debugger we can press c to continue and q to quit. There are a few more shortcuts as well; you can read more about pdb here.

When you're ready, move on to Modules Introduction

Continue