37  Python: Debug using Console

The module pdb defines an interactive source code debugger for Python programs. It supports setting (conditional) breakpoints and single stepping at the source line level, inspection of stack frames, source code listing, and evaluation of arbitrary Python code in the context of any stack frame. It also supports post-mortem debugging and can be called under program control.

For details on pdb, check the pdb documentation.

37.1 Debugging using pdb

The typical usage to break into the debugger is to insert:

import pdb

pdb.set_trace()

breakpoint()

The pdb.set_trace() or breakpoint() is almost equivalent to setting browser() in R script.

Alternatively, function can be set with breakpoints and call the function as: pdb.run

37.2 Key commands

s(tep)

Execute the current line, stop at the first possible occasion (either in a function that is called or on the next line in the current function).

n(ext) Continue execution until the next line in the current function is reached or it returns. (The difference between next and step is that step stops inside a called function, while next executes called functions at (nearly) full speed, only stopping at the next line in the current function.)

r(eturn) Continue execution until the current function returns.

c(ont(inue)) Continue execution, only stop when a breakpoint is encountered.

j(ump) lineno Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code that you don’t want to run.

whatis expression Print the type of expression.

restart [args ...] Restart the debugged Python program.

q(uit) Quit from the debugger. The program being executed is aborted.

37.3 Option 1: Using breakpoint()

Code
import numpy as np
import pdb

def fn_Mean(x, **kwargs):
    
    na_rm = kwargs.get('na_rm', None)
    
    if na_rm:
        x = x[~np.isnan(x)]
    
    n = len(x)
    AM = np.mean(x)
    
    breakpoint()
    
    GM = np.exp(np.mean(np.log(x)))
    HM = 1 / np.mean(1 / x)

    Mean = {'n': n, 'AM': AM, 'GM': GM, 'HM': HM}
    
    return Mean

A = [12, -15, 14, 18]
A = np.array(A + [np.nan])

fn_Mean(A, na_rm = True)

37.4 Option 2: Using run

Code
import numpy as np 

import pdb

import fn_Debug

A = [12, -15, 14, 18]
A = np.array(A + [np.nan])

pdb.run('fn_Debug.fn_Mean(A)')