Why can only certain variables be assigned using python debugger?

Advertisements

while debugging my code, I stumbled upon this behavior of pdb (see code below), where you can assign only certain types of variables. For clarification, I was using pandas DataFrames and wanted to assign the name of one of the columns to a new variable for quick reference, and no error was given doing just that. But when I wanted to use my new variable, I got different errors depending on how I used that variable. Where does this behavior come from and is it intended?

(Pdb) pos_frame.columns[-1]
'Position 13'
(Pdb) a = pos_frame.columns[-1]
(Pdb) b = pos_frame[a].values
*** The specified object '= pos_frame[a].values' is not a function or was not found along sys.path.
(Pdb) pos_frame[a]
*** NameError: name 'a' is not defined
(Pdb) a
(Pdb) x = 4
(Pdb) x
4

*edit
some code for recreation

import numpy as np
import pandas as pd
import pdb

# creating a DataFrame
col_list = [
    np.r_[0:50],
    np.r_[50:100]
    ]
data_frame = pd.DataFrame(col_list).transpose()
data_frame.columns = [f"Position {i}" for i in range(1, len(col_list)+1)]
pdb.set_trace()

>Solution :

a = ... and b = ... are not recognized as Python statements, as a is an abbreviation of the args command and b is an abbreviation of the break command.

  • args apparently ignores any arguments.
  • break is rejecting = pos_frame[a].values as a function or file name, just like the following error message states.
  • pos_frame[a] is unambiguously a Python (expression) statement, but as your attempt to define a earlier failed, the execution of this statement fails with the NameError shown.

Use the ! command to explicitly execute a Python statement when the statement can be recognized as a debugger command.

(Pdb) ! a = pos_fram.columns[-1]
(Pdb) ! b = pos_frame[a].values

(In general, use ! unless you know it isn’t necessary. x is not a debugger command, so there is no ambiguity whether x = 4 is a debugger command or a Python statement to execute.)

Leave a ReplyCancel reply