36  Python: Debug using VSCode

Debugging Python functions are very similar although different IDEs have slightly different setups.

In this page, we show examples using Visual Studio Code (VSCode). Generally, you can debug directly from both IDE environment.

36.1 Python script

It is the identical script shown in the previous section. It is presented here for the completeness.

Code
import numpy as np

def fn_n(x, **kwargs):
    na_rm = kwargs.get('na_rm', None)
    if na_rm:
          n = len(x[~np.isnan(x)])
    else:
          n = len(x)
    return(n)

def fn_sum(x, **kwargs):
    na_rm = kwargs.get('na_rm', None)
    if na_rm:
          out = np.nansum(x)
    else:
          out = np.sum(x)
    return(out)

def fn_prod(x, **kwargs):
    na_rm = kwargs.get('na_rm', None)
    if na_rm:
          out = np.nanprod(x)
    else:
          out = np.prod(x)
    return(out)
 
def fn_suminv(x, **kwargs):
    na_rm = kwargs.get('na_rm', None)
    if na_rm:
          out = np.nansum(1/x)
    else:
          out = np.sum(1/x)
    return(out)

def fn_AM(x, **kwargs):
  out = fn_sum(x, **kwargs)/fn_n(x, **kwargs)
  return(out)

def fn_GM(x, **kwargs):
  out = fn_prod(x, **kwargs)**(1/fn_n(x, **kwargs))
  return(out)

def fn_HM(x, **kwargs):
  out = fn_n(x, **kwargs)/fn_suminv(x, **kwargs)
  return(out)

# fn_nMean
def fn_Mean(x, **kwargs):
  n = fn_n(x, **kwargs)
  AM = fn_AM(x, **kwargs)
  GM = fn_GM(x, **kwargs)
  HM = fn_HM(x, **kwargs)
  Mean = {'n': n, 'AM': AM, 'GM': GM, 'HM': HM}
  return(Mean)


# Example

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

result = fn_Mean(A, na_rm = True)
print(result)

result = fn_Mean(A)
print(result)
{'n': 4, 'AM': 14.75, 'GM': 14.593795674586724, 'HM': 14.441260744985673}
{'n': 5, 'AM': nan, 'GM': nan, 'HM': nan}

36.2 Debugging directly in VSCode

  • Go to the Python script file with function

  • Set the breakpoint

  • Call the function under Debugger model (CTRL+SHIFT+D or Command+SHIFT+D)

36.3 VSCode Environment with breakpoint

36.4 VSCode Environment Debug Menu

36.5 VSCode Environment under Debugging Mode