Debugging and Testing in Python and R

Techniques and Best Practices for Robust Code

Learn essential techniques for debugging and unit testing in Python and R. This guide covers strategies for identifying and fixing bugs, as well as best practices for writing and running unit tests to ensure your code performs reliably.

Programming
Author
Affiliation
Published

February 14, 2024

Modified

March 11, 2025

Keywords

debugging Python, R unit testing, debugging techniques, unit testing best practices, Python testing

Introduction

Debugging and testing are crucial components of developing reliable software. Effective debugging helps you quickly identify and fix issues, while robust unit testing ensures that your code behaves as expected as it evolves. In this tutorial, we explore practical techniques for debugging and unit testing in both Python and R. Whether you are working on a data science project or building a production application, these best practices will help you write cleaner, more dependable code.



Debugging Techniques

  • Interactive Debugging with pdb:
    Python’s built-in debugger, pdb, allows you to pause code execution and inspect variables interactively.
    Example:

    #| label: python-pdb-example
    import pdb
    
    def divide(a, b):
        pdb.set_trace()  # Start debugging here
        return a / b
    
    result = divide(10, 2)
    print("Result:", result)
  • Using IDE Debuggers:
    Tools like VS Code and PyCharm provide graphical debugging tools, enabling breakpoints, step-by-step execution, and variable inspection.

  • Logging:
    Incorporate the logging module to record events and errors, which is helpful for post-mortem debugging.

    #| label: python-logging
    import logging
    
    logging.basicConfig(level=logging.INFO)
    logging.info("This is an info message.")
    logging.error("This is an error message.")
  • Using traceback() and debug():
    R’s traceback() function can be used immediately after an error to display the call stack. Additionally, debug() can be applied to functions to step through code interactively.

    #| label: r-debugging
    buggy_function <- function(x) {
      stop("An unexpected error occurred!")
    }
    tryCatch(
      buggy_function(10),
      error = function(e) {
        traceback()
        message("Error caught: ", e$message)
      }
    )
  • RStudio Debugger:
    RStudio provides an integrated debugger where you can set breakpoints, inspect variables, and step through your code.

  • Logging and Messages:
    Use message() and cat() functions to output diagnostic information during code execution.

Unit Testing Best Practices

  • Using pytest:
    The pytest framework makes it easy to write simple tests for your code.

    #| label: python-pytest-example
    def add(a, b):
        return a + b
    
    def test_add():
        assert add(2, 3) == 5
        assert add(-1, 1) == 0
    
    if __name__ == "__main__":
        import pytest
        pytest.main([__file__])
  • Test-Driven Development (TDD):
    Write tests before implementing functions to ensure your code meets requirements from the outset.

  • Using testthat:
    The testthat package provides a robust framework for writing unit tests in R.

    #| label: r-testthat-example
    library(testthat)
    
    add <- function(a, b) {
      a + b
    }
    
    test_that("add function works correctly", {
      expect_equal(add(2, 3), 5)
      expect_equal(add(-1, 1), 0)
    })
  • Integrate Testing in Your Workflow:
    Regularly run tests to catch errors early. RStudio makes it easy to run tests with built-in support for testthat.

Conclusion

Effective debugging and testing are vital to maintaining high-quality, reliable code. By leveraging tools like Python’s pdb and logging, along with R’s traceback and testthat, you can streamline your development process and catch issues early. Incorporating a robust testing strategy, whether through pytest in Python or testthat in R, ensures that your code remains maintainable and bug-free as it evolves.

Further Reading

Happy coding, and may your debugging sessions be swift and your tests pass reliably!

Back to top

Reuse

Citation

BibTeX citation:
@online{kassambara2024,
  author = {Kassambara, Alboukadel},
  title = {Debugging and {Testing} in {Python} and {R}},
  date = {2024-02-14},
  url = {https://www.datanovia.com/learn/programming/best-practices/debugging-and-testing.html},
  langid = {en}
}
For attribution, please cite this work as:
Kassambara, Alboukadel. 2024. “Debugging and Testing in Python and R.” February 14, 2024. https://www.datanovia.com/learn/programming/best-practices/debugging-and-testing.html.