Why does import pdb; pdb.set_trace trigger two different debugging scenarios when called differently in Spyder?

后端 未结 1 905
Happy的楠姐
Happy的楠姐 2021-01-25 18:55

This is a follow-up question to Stepwise debugging of selected Python code.

Why does import pdb; pdb.set_trace trigger two different debugging scena

1条回答
  •  春和景丽
    2021-01-25 19:19

    (Spyder maintainer here) I think the problem is you're trying to evaluate cells inside the scope of a function. In this case all variables are local to the scope, so you can't evaluate foo in pieces, which is what you're trying to do with our cells.

    To achieve what you want, you could use a class instead. That would allow you to save your data in variables shared by all methods in the class and to define the functions/methods you want to manipulate those data. A class would also allow you to have data and functions/methods neatly encapsulated, i.e. without being defined in the global scope of your code.

    With that, you could simply run a cell that calls the method you want to debug. In the example you posted above, this will be

    # %%
    class Foo:
        def __init__(self):
            self.names = ['A', 'B', 'C']
            self.values = [11,12,13]
    
        def manipulation(self):
            i = 0
            import pdb; pdb.set_trace()
            for n in self.names:
                variable = str(n)  + ' = ' + str(self.values[i])
                print(variable)
                i += 1      
    
    f = Foo()
    
    # %%
    f.manipulation()
    

    This allows me to debug the workings of the manipulation method without problems.

    0 讨论(0)
提交回复
热议问题