来自 Python 调试器的列表理解范围错误 [英] List comprehension scope error from Python debugger

查看:27
本文介绍了来自 Python 调试器的列表理解范围错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调试我的代码时,我想使用列表理解.但是,当我在函数内部时,我似乎无法从调试器评估列表理解.

我使用的是 Python 3.4.

脚本内容:

$ cat test.py#!/usr/bin/python定义 foo():x = [1, 2, 3, 3, 4]打印(x)富()

交互式调试:

$ python3 -mpdb test.py>/tmp/test.py(3)<模块>()->定义 foo():(Pdb) 步骤>/tmp/test.py(8)<模块>()->富()(Pdb)- 称呼 ->/tmp/test.py(3)foo()->定义 foo():(Pdb)>/tmp/test.py(4)foo()->x = [1, 2, 3, 3, 4](Pdb)>/tmp/test.py(6)foo()->打印(x)(Pdb) p [x for _ in range(1)]*** NameError: 名称 'x' 未定义(pdb) p x[1, 2, 3, 3, 4]

为什么 x 对列表理解是未知的?我如何评估调试器的列表理解,或实现等效的行为?这是一个错误,还是调试器的某种基本限制?

解决方案

在 Python 3 中,您必须在 pdb 中使用 interact 命令,然后才能访问任何由于更改而导致的非全局变量理解的实现方式.

<预><代码>>>>def foo(): [][0]...>>>富()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件<stdin>",第 1 行,在 foo 中IndexError:列表索引超出范围>>>导入 pdb;pdb.pm()><标准输入>(1)foo()(Pdb) x = 4(Pdb) [x for _ in range(2)]*** NameError: 名称 'x' 未定义(Pdb) 互动*交互的*>>>[x 代表范围内的 _(2)][4, 4]>>>

In debugging my code, I want to use a list comprehension. However, it seems I cannot evaluate a list comprehension from the debugger when I'm inside a function.

I am using Python 3.4.

Script contents:

$ cat test.py 
#!/usr/bin/python

def foo():
    x = [1, 2, 3, 3, 4]

    print(x)

foo()

Interactive debugging:

$ python3 -mpdb test.py                                                                                                                                           
> /tmp/test.py(3)<module>()
-> def foo():
(Pdb) step
> /tmp/test.py(8)<module>()
-> foo()
(Pdb) 
--Call--
> /tmp/test.py(3)foo()
-> def foo():
(Pdb) 
> /tmp/test.py(4)foo()
-> x = [1, 2, 3, 3, 4]
(Pdb) 
> /tmp/test.py(6)foo()
-> print(x)
(Pdb) p [x for _ in range(1)]
*** NameError: name 'x' is not defined
(Pdb) p x
[1, 2, 3, 3, 4]

Why is x unknown to the list comprehension? How could I evaluate a list comprehension from the debugger, or achieve an equivalent behaviour? Is this a bug, or is it some sort of fundamental limitation to the debugger?

解决方案

In Python 3, you have to use the interact command in pdb before you can access any non-global variables due to a change in the way comprehensions are implemented.

>>> def foo(): [][0]
... 
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in foo
IndexError: list index out of range
>>> import pdb;pdb.pm()
> <stdin>(1)foo()
(Pdb) x = 4
(Pdb) [x for _ in range(2)]
*** NameError: name 'x' is not defined
(Pdb) interact
*interactive*
>>> [x for _ in range(2)]
[4, 4]
>>> 

这篇关于来自 Python 调试器的列表理解范围错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆