PDB - Set or change Variable in interactive mode

Viewed 591

Currently, when I modify variables inside the interactive interpreter in pdb, it doesn't carry over outside the interactive session. Is there a way to do this?(I'm already aware of exec, !). However, I want to perform some multi-line operations.

(Pdb) c
(Pdb) pp locals()['a']
*** KeyError: 'a'
(Pdb) !a=2
(Pdb) pp locals()['a']
2
(Pdb) !del a             
(Pdb) pp locals()['a']   
*** KeyError: 'a'        
(Pdb) interact                       
*interactive*                        
>>> a=2                              
>>>                                  
now exiting InteractiveConsole...    
(Pdb) pp locals()['a']               
*** KeyError: 'a' 
2 Answers

Try below code to execute multi line code while debugging in pdb/ipdb

!import code; code.interact(local=vars())

This will enter into interactive console

The pdb is only meant for checking your code and any changes there will apply for that execution only and will not alter your code

As mentioned by Nbfour and myself in the comments above, the default pdb.Pdb class does not operate on the same namespace as that used by the current frame being debugged. Instead, the dict containing local variables is copied, and the interactive-mode works on that copied dict. This occurs in the do_interact method defined by the default Pdb class.

Subclassing pdb.Pdb, we can achieve the desired behavior:

import pdb
import code

class MyPdb(pdb.Pdb):
    def do_interact(self, arg):
        code.interact("*interactive*", local=self.curframe_locals)

MyPdb().set_trace()

Running the above script, our interactive-mode changes to local state are now permanent:

(Pdb) pp locals()['a']
*** KeyError: 'a'
(Pdb) !a=2
(Pdb) pp locals()['a']
2
(Pdb) !del a
(Pdb) pp locals()['a']
*** KeyError: 'a'
(Pdb) interact
*interactive*
>>> a=2
>>>
now exiting InteractiveConsole...
(Pdb) pp locals()['a']
2
Related