thi*_*edu 4 python debugging zip pdb
我正在尝试调试这样的函数one_away
:
import pdb
def is_one_away(first: str, other: str) -> bool:
skip_diff = {
-1: lambda i: (i, i + 1),
1: lambda i: (i + 1, i),
0: lambda i: (i + 1, i + 1)
}
try:
skip = skip_diff[len(first) - len(other)]
except KeyError:
return False
pdb.set_trace()
for i, (l1, l2) in enumerate(zip(first, other)):
if l1 != l2:
i -= 1
break
Run Code Online (Sandbox Code Playgroud)
并称之为我写道:
import one_away
one_away.is_one_away('pale', 'kale')
Run Code Online (Sandbox Code Playgroud)
运行到 时pdb.set_trace()
,我想查看 的结果zip(first ,other)
。所以我写:
(Pdb) >? list(zip(first, other))
*** Error in argument: '(zip(first, other))'
Run Code Online (Sandbox Code Playgroud)
但是如果在 Python 控制台中,它可以工作:
>>>list(zip('pale', 'kale'))
[('p', 'k'), ('a', 'a'), ('l', 'l'), ('e', 'e')]
Run Code Online (Sandbox Code Playgroud)
为什么?
list
是调试 shell 中的内置命令:
(Pdb) help list
l(ist) [first [,last] | .]
List source code for the current file. Without arguments,
list 11 lines around the current line or continue the previous
listing. With . as argument, list 11 lines around the current
line. With one argument, list 11 lines starting at that line.
With two arguments, list the given range; if the second
argument is less than the first, it is a count.
The current line in the current frame is indicated by "->".
If an exception is being debugged, the line where the
exception was originally raised or propagated is indicated by
">>", if it differs from the current line.
Run Code Online (Sandbox Code Playgroud)
所以当你输入
(Pdb) list(zip(first, other))
Run Code Online (Sandbox Code Playgroud)
它试图将其解释为传递给 pdb 的命令。相反,您想p
在 python 中执行(或rint)一个表达式:
(Pdb) list(zip(first, other))
*** Error in argument: '(zip(first, other))'
(Pdb) !list(zip(first, other))
[('p', 'k'), ('a', 'a'), ('l', 'l'), ('e', 'e')]
(Pdb) p list(zip(first, other))
[('p', 'k'), ('a', 'a'), ('l', 'l'), ('e', 'e')]
Run Code Online (Sandbox Code Playgroud)