Python Code Tips: 4 Ways to Debug Your Python Code Without IDE

Jason Zhang
Jan 6 · 5 min read
Image for post
Image for post
Created by the author

When we finish writing a piece of Python code, it often does not run well normally. That’s when we need to debug the code. Although most IDEs provide support for code debugging, we will talk about 4 fundamental python debugging methods in this article.

1. Print( )

The simplest and most common debugging method is to use print() statements to print out the suspect variable in the terminal. Almost all programming languages can use print statement to debug.

Please see the following code:

After the code runs, check the values of the variable printed out in the terminal to find out the reason for the error — division by zero.

Image for post
Image for post

Disadvantages of using print():

  • There are many useless print() in the code, and you have to delete them before the program is released. These operations may pose potential risks to the code.

2. Assert

You can use assert instead of print() to debug the code.

Rewrite the above code as follows.

The assert statement lets you test if a condition - number != 0 in your code returns True, if not, the program will raise an AssertionError and return an error message(optional).

Image for post
Image for post

The command-line option -O(capital letters) can close assert. After closing it, you can look at all the assert statements as pass statements.

Image for post
Image for post
No longer throws AssertionError

IMPORTANT: Do not add parentheses when using the assert statement.

The assert statement is mainly used for debugging and self-check and the following scenarios cannot use assert statement:

run-time error

The asset cannot check run-time error.

For example, to open a file, the following code is incorrect.

Using assert here, you assume that the file must exist. In a real scenario, the file may not exist, and when you open a file may also trigger other exceptions, so we should use try…except to handle it.

business logic

Because you can simply use the -O option to turn off assert checking so that the code in the assert will not be executed. If you put business logic into assert, such as checking permissions with assert, doing so will bring huge vulnerability to your code.

3. logging

The third way is that you can use the logging module to replace the print(). Let's rewrite the initial example as follows:

Its output looks like this.

Image for post
Image for post

The logging module provides a lot of functionality and flexibility. It can output messages not only in the terminal but also to a file. Before using the logging module, you need to set the Logging Levels. There are five levels, from the highest urgency to lowest urgency, are: CRITICAL, ERROR, WARNING, INFO, DEBUG.

The advantages of Logging compared to print are:

  • You can set different levels of urgency for messages, and filter out less urgent messages.
  • When you want to later find/remove log messages, you won’t get them confused for real print() calls.
  • If you just print to a log file, it’s easy to leave the log function calls in and just ignore them when you don’t need them.
  • With a simple configuration, a single statement can be output to different places at the same time, such as consoles and files.

For a more comprehensive overview of logging, please refer to the official tutorial(https://docs.python.org/3/library/logging.html).

4. pdb

In the last method, we use python’s built-in debugger pdb. The module pdb defines an interactive source code debugger for Python programs.

Let’s look at the example first.

Use the command -m pdb to start pdb.

$python -m pdb pdg-test.py

After starting you can use the command l to list source code, n to continue execution until the next line in the current function is reached to its returns, p expression to evaluate the expression in the current context and print its value, and finial use q to quit from the debugger.

Image for post
Image for post

In addition, you can import pdb and use pdb.set_trace() to set breakpoints in your code.

Directly use command python pdg-debug.py without -m pdb to run the code. The program will automatically break at the position of pdb.set_trace() and enter the pdb debugging environment. You can use the command p variable to view the variables or use the command c to continue to run.

Image for post
Image for post

Pdb Usage Scenarios

  • Debugging large-scale python programs
  • Debugging code in a production environment
  • Debugging multi-language mixed code

For more information about pdb, please refer to the official documentation(https://docs.python.org/3/library/pdb.html).

Conclusion

This article introduces 4 ways to debug your Python code besides IDE. During the development phase, it is most convenient to use IDE to debug the code. In addition, according to my experience, logging is the most practical and powerful.

Image for post
Image for post

Thanks for reading.

Take care, and stay all safe and healthy.

The Startup

Medium's largest active publication, followed by +756K people. Follow to join our community.

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