Six Debugging Techniques for Python Programmers

Yang Zhou
Yang Zhou
Aug 11, 2020 · 5 min read
Six Debugging Techniques for Python Programmers
Six Debugging Techniques for Python Programmers

Introduction

1. Print and Check

Print and check method

2. Assert and Check

Assert and check method
python -0 assert.py
# Traceback (most recent call last):
# ...
# ValueError: invalid literal for int() with base 10: 'Yang'

3. Using logging Module

output logging info to a file

4. pdb

A Basic Example

s = '0'
n = int(s)
print(1000 / n)
$ python -m pdb test.py
> /home/yang/test.py(1)<module>()
-> s = '0'
(Pdb) l
1 -> s = '0'
2 n = int(s)
3 print(1000 / n)
(Pdb) n
> /home/yang/test.py(2)<module>()
-> n = int(s)
(Pdb) n
> /home/yang/test.py(3)<module>()
-> print(1000 / n)
(Pdb) n
ZeroDivisionError: division by zero
> /home/yang/test.py(3)<module>()
-> print(1000 / n)
(Pdb) p s
'0'
(Pdb) p n
0

Set Trace in Code

import pdb

s = '0'
n = int(s)
pdb.set_trace()
# The program will be paused and start pdb debugger
print(1000 / n)
> /home/yang/test.py(7)<module>()
-> print(1000 / n)
(Pdb)

A More Convenient Way

s = '0'
n = int(s)
breakpoint()
print(1000 / n)
$ PYTHONBREAKPOINT = web_pdb.set_trace python3.7
$ PYTHONBREAKPOINT = 0 python3.7

5. Integrated Development Environment

6. Pen and Paper

Conclusion

TechToFreedom

Dive into technology, investment and entrepreneurship.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store