How to debug a function defined in Python console?

I saw the example below in pdb 3.12.1 document,

import pdb
def f(x):
… print(1 / x)
pdb.run(“f(2)”)
(1)()
(Pdb) continue
0.5

It looks great! Then I tried mine,

def foo(x):
… y = x + 1
… print(y)
… z = y + 1

pdb.run(“foo(5)”)
(1)()->None
(Pdb) next
6
–Return–
(1)()->None
(Pdb) y
*** NameError: name ‘y’ is not defined
(Pdb) quit

Hmm…no luck! How to step in it?

You could try the IDLE debugger.

>>> def f(x):
...    y = x+1
...    z = 2*y
...    return

>>> [DEBUG ON]
>>> f(3)

At this point, [step] 3 times in the debugger window and x 3, y 4, and z 8 successively appear in the locals window.

The problem was caused by the first command “next” following “run”. If changed to “step”, then it works.

pdb.run(“foo(5)”)
(1)()
(Pdb) step
–Call–
(1)foo()
(Pdb) next
(2)foo()
(Pdb) y
*** NameError: name ‘y’ is not defined
(Pdb) next
(3)foo()
(Pdb) y
6
(Pdb) step
6
(4)foo()
(Pdb) next
–Return–
(4)foo()->None
(Pdb) z
7
(Pdb) cont

Because there is no file involved, commands which are lineno related will not work, including the “break”:frowning: